Skip to content

Commit f9dc8b2

Browse files
authored
Merge pull request #1292 from ZedThree/unit-test-work-with-pytest
Allow running unit tests with pytest
2 parents 2e266e1 + 66cde64 commit f9dc8b2

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

57 files changed

+231
-237
lines changed

pyproject.toml

+3
Original file line numberDiff line numberDiff line change
@@ -72,3 +72,6 @@ where = ["src"]
7272

7373
[tool.setuptools.package-data]
7474
"netCDF4.plugins" = ["lib__nc*"]
75+
76+
[tool.pytest.ini_options]
77+
pythonpath = ["test"]

test/__init__.py

Whitespace-only changes.

test/filter_availability.py

+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
from tempfile import NamedTemporaryFile
2+
from netCDF4 import (
3+
Dataset,
4+
__has_zstandard_support__,
5+
__has_bzip2_support__,
6+
__has_blosc_support__,
7+
__has_szip_support__,
8+
)
9+
import os
10+
11+
# True if plugins have been disabled
12+
no_plugins = os.getenv("NO_PLUGINS")
13+
14+
15+
with NamedTemporaryFile(suffix=".nc", delete=False) as tf:
16+
with Dataset(tf.name, "w") as nc:
17+
has_zstd_filter = __has_zstandard_support__ and nc.has_zstd_filter()
18+
has_bzip2_filter = __has_bzip2_support__ and nc.has_bzip2_filter()
19+
has_blosc_filter = __has_blosc_support__ and nc.has_blosc_filter()
20+
has_szip_filter = __has_szip_support__ and nc.has_szip_filter()

test/run_all.py

+5-58
Original file line numberDiff line numberDiff line change
@@ -1,66 +1,13 @@
11
import glob, os, sys, unittest, struct, tempfile
2-
from netCDF4 import getlibversion,__hdf5libversion__,__netcdf4libversion__,__version__, Dataset
3-
from netCDF4 import __has_cdf5_format__, __has_nc_inq_path__, __has_nc_create_mem__, \
4-
__has_parallel4_support__, __has_pnetcdf_support__, \
5-
__has_zstandard_support__, __has_bzip2_support__, \
6-
__has_blosc_support__,__has_quantization_support__,\
7-
__has_szip_support__
8-
2+
from netCDF4 import __hdf5libversion__,__netcdf4libversion__,__version__, Dataset
93
# can also just run
104
# python -m unittest discover . 'tst*py'
115

126
# Find all test files.
13-
test_files = glob.glob('tst_*.py')
14-
if __netcdf4libversion__ < '4.2.1' or __has_parallel4_support__ or __has_pnetcdf_support__:
15-
test_files.remove('tst_diskless.py')
16-
sys.stdout.write('not running tst_diskless.py ...\n')
17-
if not __has_nc_inq_path__:
18-
test_files.remove('tst_filepath.py')
19-
sys.stdout.write('not running tst_filepath.py ...\n')
20-
if not __has_nc_create_mem__:
21-
test_files.remove('tst_create_mem.py')
22-
sys.stdout.write('not running tst_create_mem.py ...\n')
23-
if not __has_cdf5_format__ or struct.calcsize("P") < 8:
24-
test_files.remove('tst_cdf5.py')
25-
sys.stdout.write('not running tst_cdf5.py ...\n')
26-
if not __has_quantization_support__:
27-
test_files.remove('tst_compression_quant.py')
28-
sys.stdout.write('not running tst_compression_quant.py ...\n')
29-
filename = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
30-
nc = Dataset(filename,'w')
31-
if not __has_zstandard_support__ or os.getenv('NO_PLUGINS') or not nc.has_zstd_filter():
32-
test_files.remove('tst_compression_zstd.py')
33-
sys.stdout.write('not running tst_compression_zstd.py ...\n')
34-
if not __has_bzip2_support__ or os.getenv('NO_PLUGINS') or not nc.has_bzip2_filter():
35-
test_files.remove('tst_compression_bzip2.py')
36-
sys.stdout.write('not running tst_compression_bzip2.py ...\n')
37-
if not __has_blosc_support__ or os.getenv('NO_PLUGINS') or not nc.has_blosc_filter():
38-
test_files.remove('tst_compression_blosc.py')
39-
sys.stdout.write('not running tst_compression_blosc.py ...\n')
40-
if not __has_szip_support__ or not nc.has_szip_filter():
41-
test_files.remove('tst_compression_szip.py')
42-
sys.stdout.write('not running tst_compression_szip.py ...\n')
43-
nc.close()
44-
os.remove(filename)
45-
46-
# Don't run tests that require network connectivity
47-
if os.getenv('NO_NET'):
48-
test_files.remove('tst_dap.py');
49-
sys.stdout.write('not running tst_dap.py ...\n')
50-
else:
51-
# run opendap test first (issue #856).
52-
test_files.remove('tst_dap.py')
53-
test_files.insert(0,'tst_dap.py')
54-
55-
# Don't run CDL test (that requires ncdump/ncgen)
56-
if os.getenv('NO_CDL'):
57-
test_files.remove('tst_cdl.py');
58-
sys.stdout.write('not running tst_cdl.py ...\n')
59-
60-
# Don't run computationally intensive test
61-
if not os.getenv('MEMORY_LEAK_TEST'):
62-
test_files.remove('tst_multiple_open_close.py');
63-
sys.stdout.write('not running tst_multiple_open_close.py ...\n')
7+
test_files = glob.glob('test_*.py')
8+
# run opendap test first (issue #856).
9+
test_files.remove('test_dap.py')
10+
test_files.insert(0,'test_dap.py')
6411

6512
# Build the test suite from the tests found in the test files.
6613
testsuite = unittest.TestSuite()

test/test_Unsigned.py

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import unittest
2+
import netCDF4
3+
from numpy.testing import assert_array_equal
4+
import numpy as np
5+
import pathlib
6+
7+
test_dir = pathlib.Path(__file__).parent
8+
9+
10+
class Test_Unsigned(unittest.TestCase):
11+
"""
12+
Test autoconversion to unsigned ints when _Unsigned attribute is True.
13+
This attribute is is set by netcdf-java to designate unsigned
14+
integer data stored with a signed integer type in netcdf-3.
15+
If _Unsigned=True, a view to the data as unsigned integers is returned.
16+
set_autoscale can be used to turn this off (default is on)
17+
See issue #656 (pull request #658).
18+
"""
19+
def test_unsigned(self):
20+
with netCDF4.Dataset(test_dir / "ubyte.nc") as f:
21+
data = f['ub'][:]
22+
assert data.dtype.str[1:] == 'u1'
23+
assert_array_equal(data,np.array([0,255],np.uint8))
24+
f.set_auto_scale(False)
25+
data2 = f['ub'][:]
26+
assert data2.dtype.str[1:] == 'i1'
27+
assert_array_equal(data2,np.array([0,-1],np.int8))
28+
data = f['sb'][:]
29+
assert data.dtype.str[1:] == 'i1'
30+
# issue #1232 _Unsigned='false' is same as not having _Unsigned set.
31+
data = f['sb2'][:]
32+
assert data.dtype.str[1:] == 'i1'
33+
34+
# issue 671
35+
with netCDF4.Dataset(test_dir / "issue671.nc") as f:
36+
data1 = f['soil_moisture'][:]
37+
assert(np.ma.isMA(data1))
38+
f.set_auto_scale(False)
39+
data2 = f['soil_moisture'][:]
40+
assert(data1.mask.sum() == data2.mask.sum())
41+
42+
# issue 794
43+
# test that valid_min/valid_max/_FillValue are
44+
# treated as unsigned integers.
45+
with netCDF4.Dataset(test_dir / "20171025_2056.Cloud_Top_Height.nc") as f:
46+
data = f['HT'][:]
47+
assert(data.mask.sum() == 57432)
48+
assert(int(data.max()) == 15430)
49+
assert(int(data.min()) == 0)
50+
assert(data.dtype == np.float32)
51+
52+
53+
if __name__ == '__main__':
54+
unittest.main()
File renamed without changes.

test/tst_atts.py renamed to test/test_atts.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
import os
66
import tempfile
77
import warnings
8+
import pathlib
89

910
import numpy as np
1011
from collections import OrderedDict
@@ -219,9 +220,8 @@ def runTest(self):
219220
assert getattr(v1,'nonexistantatt',None) == None
220221

221222
# issue 915 empty string attribute (ncdump reports 'NIL')
222-
f = netCDF4.Dataset('test_gold.nc')
223-
assert f['RADIANCE'].VAR_NOTES == ""
224-
f.close()
223+
with netCDF4.Dataset(pathlib.Path(__file__).parent / "test_gold.nc") as f:
224+
assert f['RADIANCE'].VAR_NOTES == ""
225225

226226
if __name__ == '__main__':
227227
unittest.main()

test/tst_cdf5.py renamed to test/test_cdf5.py

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,17 @@
1-
from netCDF4 import Dataset
1+
from netCDF4 import Dataset, __has_cdf5_format__
22
import numpy as np
33
import sys, os, unittest, tempfile
4+
import struct
45
from numpy.testing import assert_array_equal
56

67
FILE_NAME = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
78
dimsize = np.iinfo(np.int32).max*2 # only allowed in CDF5
89
ndim = 100
910
arrdata = np.random.randint(np.iinfo(np.uint8).min,np.iinfo(np.uint8).max,size=ndim)
1011

11-
class test_cdf5(unittest.TestCase):
1212

13+
@unittest.skipIf(not __has_cdf5_format__ or struct.calcsize("P") < 8, "no CDF5 support")
14+
class test_cdf5(unittest.TestCase):
1315
def setUp(self):
1416
self.netcdf_file = FILE_NAME
1517
nc = Dataset(self.netcdf_file,'w',format='NETCDF3_64BIT_DATA')

test/test_cdl.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
import unittest
2+
import netCDF4
3+
import os
4+
import pathlib
5+
6+
test_ncdump="""netcdf ubyte {
7+
dimensions:
8+
d = 2 ;
9+
variables:
10+
byte ub(d) ;
11+
ub:_Unsigned = "true" ;
12+
byte sb(d) ;
13+
byte sb2(d) ;
14+
sb2:_Unsigned = "false" ;
15+
16+
// global attributes:
17+
:_Format = "classic" ;
18+
}
19+
"""
20+
test_ncdump2="""netcdf ubyte {
21+
dimensions:
22+
d = 2 ;
23+
variables:
24+
byte ub(d) ;
25+
ub:_Unsigned = "true" ;
26+
byte sb(d) ;
27+
byte sb2(d) ;
28+
sb2:_Unsigned = "false" ;
29+
30+
// global attributes:
31+
:_Format = "classic" ;
32+
data:
33+
34+
ub = 0, -1 ;
35+
36+
sb = -128, 127 ;
37+
38+
sb2 = -127, -127 ;
39+
}
40+
"""
41+
42+
43+
ubyte_filename = pathlib.Path(__file__).parent / "ubyte.nc"
44+
45+
46+
@unittest.skipIf(os.getenv("NO_CDL"), "CDL test disabled")
47+
class Test_CDL(unittest.TestCase):
48+
"""
49+
Test import/export of CDL
50+
"""
51+
52+
def setUp(self):
53+
with netCDF4.Dataset(ubyte_filename) as f:
54+
f.tocdl(outfile="ubyte.cdl", data=True)
55+
56+
def test_tocdl(self):
57+
# treated as unsigned integers.
58+
with netCDF4.Dataset(ubyte_filename) as f:
59+
assert f.tocdl() == test_ncdump
60+
assert f.tocdl(data=True) == test_ncdump2
61+
62+
def test_fromcdl(self):
63+
with netCDF4.Dataset.fromcdl("ubyte.cdl", ncfilename="ubyte2.nc") as f1:
64+
with netCDF4.Dataset(ubyte_filename) as f2:
65+
assert f1.variables.keys() == f2.variables.keys()
66+
assert f1.filepath() == "ubyte2.nc"
67+
assert f1.dimensions.keys() == f2.dimensions.keys()
68+
assert len(f1.dimensions["d"]) == len(f2.dimensions["d"])
69+
assert (f1["ub"][:] == f2["ub"][:]).all()
70+
assert (f1["sb"][:] == f2["sb"][:]).all()
71+
72+
os.remove("ubyte2.nc")
73+
74+
def tearDown(self):
75+
# Remove the temporary files
76+
os.remove('ubyte.cdl')
77+
78+
if __name__ == '__main__':
79+
unittest.main()
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.

test/tst_compression_blosc.py renamed to test/test_compression_blosc.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22
from netCDF4 import Dataset
33
from numpy.testing import assert_almost_equal
44
import os, tempfile, unittest, sys
5+
from filter_availability import no_plugins, has_blosc_filter
6+
57

68
ndim = 100000
79
iblosc_shuffle=2
@@ -31,8 +33,9 @@ def write_netcdf(filename,dtype='f8',blosc_shuffle=1,complevel=6):
3133
foo_zstd[:] = datarr
3234
nc.close()
3335

34-
class CompressionTestCase(unittest.TestCase):
3536

37+
@unittest.skipIf(no_plugins or not has_blosc_filter, "blosc filter not available")
38+
class CompressionTestCase(unittest.TestCase):
3639
def setUp(self):
3740
self.filename = filename
3841
write_netcdf(self.filename,complevel=iblosc_complevel,blosc_shuffle=iblosc_shuffle)
@@ -73,10 +76,6 @@ def runTest(self):
7376
assert f.variables['data_zstd'].filters() == dtest
7477
f.close()
7578

79+
7680
if __name__ == '__main__':
77-
nc = Dataset(filename,'w')
78-
if not nc.has_blosc_filter():
79-
sys.stdout.write('blosc filter not available, skipping tests ...\n')
80-
else:
81-
nc.close()
82-
unittest.main()
81+
unittest.main()

test/tst_compression_bzip2.py renamed to test/test_compression_bzip2.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from netCDF4 import Dataset
33
from numpy.testing import assert_almost_equal
44
import os, tempfile, unittest, sys
5+
from filter_availability import no_plugins, has_bzip2_filter
56

67
ndim = 100000
78
filename1 = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
@@ -16,8 +17,9 @@ def write_netcdf(filename,dtype='f8',complevel=6):
1617
foo[:] = array
1718
nc.close()
1819

19-
class CompressionTestCase(unittest.TestCase):
2020

21+
@unittest.skipIf(no_plugins or not has_bzip2_filter, "bzip2 filter not available")
22+
class CompressionTestCase(unittest.TestCase):
2123
def setUp(self):
2224
self.filename1 = filename1
2325
self.filename2 = filename2
@@ -48,10 +50,6 @@ def runTest(self):
4850
assert(size < 0.96*uncompressed_size)
4951
f.close()
5052

53+
5154
if __name__ == '__main__':
52-
nc = Dataset(filename1,'w')
53-
if not nc.has_bzip2_filter():
54-
sys.stdout.write('bzip2 filter not available, skipping tests ...\n')
55-
else:
56-
nc.close()
57-
unittest.main()
55+
unittest.main()

test/tst_compression_quant.py renamed to test/test_compression_quant.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from numpy.random.mtrand import uniform
2-
from netCDF4 import Dataset
2+
from netCDF4 import Dataset, __has_quantization_support__
33
from numpy.testing import assert_almost_equal
44
import numpy as np
55
import os, tempfile, unittest
@@ -25,8 +25,9 @@ def write_netcdf(filename,zlib,significant_digits,data,dtype='f8',shuffle=False,
2525
data = file.variables['data'][:]
2626
file.close()
2727

28-
class CompressionTestCase(unittest.TestCase):
2928

29+
@unittest.skipIf(not __has_quantization_support__, "missing quantisation support")
30+
class CompressionTestCase(unittest.TestCase):
3031
def setUp(self):
3132
self.files = files
3233
# no compression

test/tst_compression_szip.py renamed to test/test_compression_szip.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
from netCDF4 import Dataset
33
from numpy.testing import assert_almost_equal
44
import os, tempfile, unittest, sys
5+
from filter_availability import has_szip_filter
56

67
ndim = 100000
78
filename = tempfile.NamedTemporaryFile(suffix='.nc', delete=False).name
@@ -18,8 +19,9 @@ def write_netcdf(filename,dtype='f8'):
1819
foo_szip[:] = datarr
1920
nc.close()
2021

21-
class CompressionTestCase(unittest.TestCase):
2222

23+
@unittest.skipIf(not has_szip_filter, "szip filter not available")
24+
class CompressionTestCase(unittest.TestCase):
2325
def setUp(self):
2426
self.filename = filename
2527
write_netcdf(self.filename)
@@ -38,10 +40,6 @@ def runTest(self):
3840
assert f.variables['data_szip'].filters() == dtest
3941
f.close()
4042

43+
4144
if __name__ == '__main__':
42-
nc = Dataset(filename,'w')
43-
if not nc.has_szip_filter():
44-
sys.stdout.write('szip filter not available, skipping tests ...\n')
45-
else:
46-
nc.close()
47-
unittest.main()
45+
unittest.main()

0 commit comments

Comments
 (0)