diff --git a/.gitignore b/.gitignore index 331398c60..849632b5f 100644 --- a/.gitignore +++ b/.gitignore @@ -12,9 +12,9 @@ *.dylib build/ dist/ -mapnik/paths.py *.egg-info/ .eggs/ .mason/ mason_packages/ mapnik/plugins +_skbuild/ diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 000000000..4d0894ced --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,66 @@ +cmake_minimum_required(VERSION 3.15) +include(cmake/vcpkg_setup.cmake) +project(${SKBUILD_PROJECT_NAME} LANGUAGES CXX VERSION ${SKBUILD_PROJECT_VERSION}) + +find_package(Python COMPONENTS Interpreter Development.Module) +find_package(mapnik CONFIG REQUIRED) +find_package(Boost REQUIRED COMPONENTS thread python${Python_VERSION_MAJOR}${Python_VERSION_MINOR}) + +#set(Python_SOABI ${SKBUILD_SOABI}) +Python_add_library(_mapnik MODULE) +target_link_libraries(_mapnik PRIVATE + mapnik::mapnik + mapnik::json + mapnik::wkt + # even though boost_thread is no longer used in mapnik core + # we need to link in for boost_python to avoid missing symbol: _ZN5boost6detail12get_tss_dataEPKv / boost::detail::get_tss_data + Boost::thread + Boost::python${Python_VERSION_MAJOR}${Python_VERSION_MINOR} + ICU::data ICU::i18n ICU::uc +) +target_sources(_mapnik PRIVATE + src/boost_std_shared_shim.hpp + src/mapnik_color.cpp + src/mapnik_coord.cpp + src/mapnik_datasource_cache.cpp + src/mapnik_datasource.cpp + src/mapnik_enumeration_wrapper_converter.hpp + src/mapnik_enumeration.hpp + src/mapnik_envelope.cpp + src/mapnik_expression.cpp + src/mapnik_feature.cpp + src/mapnik_featureset.cpp + src/mapnik_font_engine.cpp + src/mapnik_fontset.cpp + src/mapnik_gamma_method.cpp + src/mapnik_geometry.cpp + src/mapnik_grid_view.cpp + src/mapnik_grid.cpp + src/mapnik_image_view.cpp + src/mapnik_image.cpp + src/mapnik_label_collision_detector.cpp + src/mapnik_layer.cpp + src/mapnik_logger.cpp + src/mapnik_map.cpp + src/mapnik_palette.cpp + src/mapnik_parameters.cpp + src/mapnik_proj_transform.cpp + src/mapnik_projection.cpp + src/mapnik_python.cpp + src/mapnik_query.cpp + src/mapnik_raster_colorizer.cpp + src/mapnik_rule.cpp + src/mapnik_scaling_method.cpp + src/mapnik_style.cpp + src/mapnik_svg.hpp + src/mapnik_symbolizer.cpp + src/mapnik_threads.hpp + src/mapnik_value_converter.hpp + src/mapnik_view_transform.cpp + src/python_grid_utils.cpp + src/python_grid_utils.hpp + src/python_optional.hpp + src/python_to_value.hpp +) + +install(TARGETS _mapnik LIBRARY DESTINATION ${SKBUILD_PROJECT_NAME}) diff --git a/build.py b/build.py deleted file mode 100644 index 0f94826b6..000000000 --- a/build.py +++ /dev/null @@ -1,120 +0,0 @@ -import glob -import os -from subprocess import Popen, PIPE -from distutils import sysconfig - -Import('env') - -def call(cmd, silent=True): - stdin, stderr = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() - if not stderr: - return stdin.strip() - elif not silent: - print stderr - - -prefix = env['PREFIX'] -target_path = os.path.normpath(sysconfig.get_python_lib() + os.path.sep + env['MAPNIK_NAME']) - -py_env = env.Clone() - -py_env.Append(CPPPATH = sysconfig.get_python_inc()) - -py_env.Append(CPPDEFINES = env['LIBMAPNIK_DEFINES']) - -py_env['LIBS'] = [env['MAPNIK_NAME'],'libboost_python'] - -link_all_libs = env['LINKING'] == 'static' or env['RUNTIME_LINK'] == 'static' - -# even though boost_thread is no longer used in mapnik core -# we need to link in for boost_python to avoid missing symbol: _ZN5boost6detail12get_tss_dataEPKv / boost::detail::get_tss_data -py_env.AppendUnique(LIBS = 'boost_thread%s' % env['BOOST_APPEND']) - -if link_all_libs: - py_env.AppendUnique(LIBS=env['LIBMAPNIK_LIBS']) - -# note: on linux -lrt must be linked after thread to avoid: undefined symbol: clock_gettime -if env['RUNTIME_LINK'] == 'static' and env['PLATFORM'] == 'Linux': - py_env.AppendUnique(LIBS='rt') - -# TODO - do solaris/fedora need direct linking too? -python_link_flag = '' -if env['PLATFORM'] == 'Darwin': - python_link_flag = '-undefined dynamic_lookup' - -paths = ''' -"""Configuration paths of Mapnik fonts and input plugins (auto-generated by SCons).""" - -from os.path import normpath,join,dirname - -mapniklibpath = '%s' -mapniklibpath = normpath(join(dirname(__file__),mapniklibpath)) -''' - -paths += "inputpluginspath = join(mapniklibpath,'input')\n" - -if env['SYSTEM_FONTS']: - paths += "fontscollectionpath = normpath('%s')\n" % env['SYSTEM_FONTS'] -else: - paths += "fontscollectionpath = join(mapniklibpath,'fonts')\n" - -paths += "__all__ = [mapniklibpath,inputpluginspath,fontscollectionpath]\n" - -if not os.path.exists(env['MAPNIK_NAME']): - os.mkdir(env['MAPNIK_NAME']) - -file('mapnik/paths.py','w').write(paths % (env['MAPNIK_LIB_DIR'])) - -# force open perms temporarily so that `sudo scons install` -# does not later break simple non-install non-sudo rebuild -try: - os.chmod('mapnik/paths.py',0666) -except: pass - -# install the shared object beside the module directory -sources = glob.glob('src/*.cpp') - -if 'install' in COMMAND_LINE_TARGETS: - # install the core mapnik python files, including '__init__.py' - init_files = glob.glob('mapnik/*.py') - if 'mapnik/paths.py' in init_files: - init_files.remove('mapnik/paths.py') - init_module = env.Install(target_path, init_files) - env.Alias(target='install', source=init_module) - # fix perms and install the custom generated 'paths.py' - targetp = os.path.join(target_path,'paths.py') - env.Alias("install", targetp) - # use env.Command rather than env.Install - # to enable setting proper perms on `paths.py` - env.Command( targetp, 'mapnik/paths.py', - [ - Copy("$TARGET","$SOURCE"), - Chmod("$TARGET", 0644), - ]) - -if 'uninstall' not in COMMAND_LINE_TARGETS: - if env['HAS_CAIRO']: - py_env.Append(CPPPATH = env['CAIRO_CPPPATHS']) - py_env.Append(CPPDEFINES = '-DHAVE_CAIRO') - if link_all_libs: - py_env.Append(LIBS=env['CAIRO_ALL_LIBS']) - - if env['HAS_PYCAIRO']: - py_env.Append(CPPDEFINES = '-DHAVE_PYCAIRO') - py_env.Append(CPPPATH = env['PYCAIRO_PATHS']) - -py_env.Append(LINKFLAGS=python_link_flag) -py_env.AppendUnique(LIBS='mapnik-json') -py_env.AppendUnique(LIBS='mapnik-wkt') - -_mapnik = py_env.LoadableModule('mapnik/_mapnik', sources, LDMODULEPREFIX='', LDMODULESUFFIX='.so') - -Depends(_mapnik, env.subst('../../src/%s' % env['MAPNIK_LIB_NAME'])) -Depends(_mapnik, env.subst('../../src/json/libmapnik-json${LIBSUFFIX}')) -Depends(_mapnik, env.subst('../../src/wkt/libmapnik-wkt${LIBSUFFIX}')) - -if 'uninstall' not in COMMAND_LINE_TARGETS: - pymapniklib = env.Install(target_path,_mapnik) - py_env.Alias(target='install',source=pymapniklib) - -env['create_uninstall_target'](env, target_path) diff --git a/cmake/vcpkg_setup.cmake b/cmake/vcpkg_setup.cmake new file mode 100644 index 000000000..8f3e42cbd --- /dev/null +++ b/cmake/vcpkg_setup.cmake @@ -0,0 +1,4 @@ +if(WIN32) + set(VCPKG_TARGET_TRIPLET x64-windows-static) +endif() +set(CMAKE_TOOLCHAIN_FILE "~/vcpkg/scripts/buildsystems/vcpkg.cmake") diff --git a/mapnik/paths.py b/mapnik/paths.py new file mode 100644 index 000000000..4cd1fa52d --- /dev/null +++ b/mapnik/paths.py @@ -0,0 +1,7 @@ +import os + +mapniklibpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "lib") +inputpluginspath = os.path.join(mapniklibpath, 'mapnik', 'input') +fontscollectionpath = os.path.join(mapniklibpath, 'mapnik', 'fonts') + +__all__ = [mapniklibpath,inputpluginspath,fontscollectionpath] diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 000000000..15a79fa8b --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,27 @@ +[project] +name = "mapnik" +version = "4.0.0" +authors = [ + { name="Blake Thompson", email="flippmoke@gmail.com" }, +] +description = "Python bindings for Mapnik" +readme = "README.md" +requires-python = ">=3.7" + +[project.urls] +"Homepage" = "https://github.com/mapnik/python-mapnik" +"Bug Tracker" = "https://github.com/mapnik/python-mapnik/issues" + +[project.optional-dependencies] +test = ["pytest"] + +[build-system] +requires = ["scikit-build-core"] +build-backend = "scikit_build_core.build" + +[tool.scikit-build] +cmake.minimum-version = "3.15" +cmake.build-type = "Release" +sdist.reproducible = true +wheel.packages = ["mapnik"] +#build-dir = "build" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index f4ca59d33..000000000 --- a/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[nosetests] -verbosity=1 diff --git a/setup.py b/setup.py deleted file mode 100755 index 9985da5a2..000000000 --- a/setup.py +++ /dev/null @@ -1,317 +0,0 @@ -#! /usr/bin/env python - -import os -import os.path -import re -import shutil -import subprocess -import sys -import glob -from distutils import sysconfig -from ctypes.util import find_library - -from setuptools import Command, Extension, setup - -PYTHON3 = sys.version_info.major == 3 - - -# Utils -def check_output(args): - output = subprocess.check_output(args) - if PYTHON3: - # check_output returns bytes in PYTHON3. - output = output.decode() - return output.rstrip('\n') - - -def clean_boost_name(name): - name = name.split('.')[0] - if name.startswith('lib'): - name = name[3:] - return name - - -def find_boost_library(_id): - suffixes = [ - "", # standard naming - "-mt" # former naming schema for multithreading build - ] - if "python" in _id: - # Debian naming convention for versions installed in parallel - suffixes.insert(0, "-py%d%d" % (sys.version_info.major, - sys.version_info.minor)) - suffixes.insert(1, "%d%d" % (sys.version_info.major, - sys.version_info.minor)) - # standard suffix for Python3 - suffixes.insert(2, sys.version_info.major) - for suf in suffixes: - name = "%s%s" % (_id, suf) - lib = find_library(name) - if lib is not None: - return name - - -def get_boost_library_names(): - wanted = ['boost_python', 'boost_thread', 'boost_system'] - found = [] - missing = [] - for _id in wanted: - name = os.environ.get("%s_LIB" % _id.upper(), find_boost_library(_id)) - if name: - found.append(name) - else: - missing.append(_id) - if missing: - msg = "" - for name in missing: - msg += ("\nMissing {} boost library, try to add its name with " - "{}_LIB environment var.").format(name, name.upper()) - raise EnvironmentError(msg) - return found - - -class WhichBoostCommand(Command): - description = 'Output found boost names. Useful for debug.' - user_options = [] - - def initialize_options(self): - pass - - def finalize_options(self): - pass - - def run(self): - print("\n".join(get_boost_library_names())) - - -cflags = sysconfig.get_config_var('CFLAGS') -sysconfig._config_vars['CFLAGS'] = re.sub( - ' +', ' ', cflags.replace('-g ', '').replace('-Os', '').replace('-arch i386', '')) -opt = sysconfig.get_config_var('OPT') -sysconfig._config_vars['OPT'] = re.sub( - ' +', ' ', opt.replace('-g ', '').replace('-Os', '')) -ldshared = sysconfig.get_config_var('LDSHARED') -sysconfig._config_vars['LDSHARED'] = re.sub( - ' +', ' ', ldshared.replace('-g ', '').replace('-Os', '').replace('-arch i386', '')) -ldflags = sysconfig.get_config_var('LDFLAGS') -sysconfig._config_vars['LDFLAGS'] = re.sub( - ' +', ' ', ldflags.replace('-g ', '').replace('-Os', '').replace('-arch i386', '')) -pycflags = sysconfig.get_config_var('PY_CFLAGS') -sysconfig._config_vars['PY_CFLAGS'] = re.sub( - ' +', ' ', pycflags.replace('-g ', '').replace('-Os', '').replace('-arch i386', '')) -sysconfig._config_vars['CFLAGSFORSHARED'] = '' -os.environ['ARCHFLAGS'] = '' - -if os.environ.get("MASON_BUILD", "false") == "true": - # run bootstrap.sh to get mason builds - subprocess.call(['./bootstrap.sh']) - mapnik_config = 'mason_packages/.link/bin/mapnik-config' - mason_build = True -else: - mapnik_config = 'mapnik-config' - mason_build = False - - -linkflags = [] -lib_path = os.path.join(check_output([mapnik_config, '--prefix']),'lib') -linkflags.extend(check_output([mapnik_config, '--libs']).split(' ')) -linkflags.extend(check_output([mapnik_config, '--ldflags']).split(' ')) -linkflags.extend(check_output([mapnik_config, '--dep-libs']).split(' ')) -linkflags.extend([ -'-lmapnik-wkt', -'-lmapnik-json', -] + ['-l%s' % i for i in get_boost_library_names()]) - -# Dynamically make the mapnik/paths.py file -f_paths = open('mapnik/paths.py', 'w') -f_paths.write('import os\n') -f_paths.write('\n') - -input_plugin_path = check_output([mapnik_config, '--input-plugins']) -font_path = check_output([mapnik_config, '--fonts']) - -if mason_build: - try: - if sys.platform == 'darwin': - base_f = 'libmapnik.dylib' - else: - base_f = 'libmapnik.so' - f = os.path.join(lib_path, base_f) - if not os.path.exists(os.path.join('mapnik', 'lib')): - os.makedirs(os.path.join('mapnik', 'lib')) - shutil.copyfile(f, os.path.join('mapnik', 'lib', base_f)) - except shutil.Error: - pass - input_plugin_files = os.listdir(input_plugin_path) - input_plugin_files = [os.path.join( - input_plugin_path, f) for f in input_plugin_files] - if not os.path.exists(os.path.join('mapnik', 'lib', 'mapnik', 'input')): - os.makedirs(os.path.join('mapnik', 'lib', 'mapnik', 'input')) - for f in input_plugin_files: - try: - shutil.copyfile(f, os.path.join( - 'mapnik', 'lib', 'mapnik', 'input', os.path.basename(f))) - except shutil.Error: - pass - font_files = os.listdir(font_path) - font_files = [os.path.join(font_path, f) for f in font_files] - if not os.path.exists(os.path.join('mapnik', 'lib', 'mapnik', 'fonts')): - os.makedirs(os.path.join('mapnik', 'lib', 'mapnik', 'fonts')) - for f in font_files: - try: - shutil.copyfile(f, os.path.join( - 'mapnik', 'lib', 'mapnik', 'fonts', os.path.basename(f))) - except shutil.Error: - pass - f_paths.write( - 'mapniklibpath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "lib")\n') - f_paths.write("inputpluginspath = os.path.join(mapniklibpath, 'mapnik', 'input')\n") - f_paths.write("fontscollectionpath = os.path.join(mapniklibpath, 'mapnik', 'fonts')\n") - f_paths.write( - "__all__ = [mapniklibpath,inputpluginspath,fontscollectionpath]\n") - f_paths.close() -else: - if os.environ.get('LIB_DIR_NAME'): - mapnik_lib_path = lib_path + os.environ.get('LIB_DIR_NAME') - else: - mapnik_lib_path = lib_path + "/mapnik" - f_paths.write("mapniklibpath = '{path}'\n".format(path=mapnik_lib_path)) - f_paths.write('mapniklibpath = os.path.normpath(mapniklibpath)\n') - f_paths.write( - "inputpluginspath = '{path}'\n".format(path=input_plugin_path)) - f_paths.write( - "fontscollectionpath = '{path}'\n".format(path=font_path)) - f_paths.write( - "__all__ = [mapniklibpath,inputpluginspath,fontscollectionpath]\n") - f_paths.close() - - -if mason_build: - - share_dir = 'share' - - for dep in ['icu','gdal','proj']: - share_path = os.path.join('mapnik', share_dir, dep) - if not os.path.exists(share_path): - os.makedirs(share_path) - - icu_path = 'mason_packages/.link/share/icu/*/*.dat' - icu_files = glob.glob(icu_path) - if len(icu_files) != 1: - raise Exception("Failed to find icu dat file at "+ icu_path) - for f in icu_files: - shutil.copyfile(f, os.path.join( - 'mapnik', share_dir, 'icu', os.path.basename(f))) - - gdal_path = 'mason_packages/.link/share/gdal/' - gdal_files = os.listdir(gdal_path) - gdal_files = [os.path.join(gdal_path, f) for f in gdal_files] - for f in gdal_files: - try: - shutil.copyfile(f, os.path.join( - 'mapnik', share_dir, 'gdal', os.path.basename(f))) - except shutil.Error: - pass - - proj_path = 'mason_packages/.link/share/proj/' - proj_files = os.listdir(proj_path) - proj_files = [os.path.join(proj_path, f) for f in proj_files] - for f in proj_files: - try: - shutil.copyfile(f, os.path.join( - 'mapnik', share_dir, 'proj', os.path.basename(f))) - except shutil.Error: - pass - -extra_comp_args = check_output([mapnik_config, '--cflags']).split(' ') - -extra_comp_args = list(filter(lambda arg: arg != "-fvisibility=hidden", extra_comp_args)) - -if os.environ.get("PYCAIRO", "false") == "true": - try: - extra_comp_args.append('-DHAVE_PYCAIRO') - print("-I%s/include/pycairo".format(sys.exec_prefix)) - extra_comp_args.append("-I{0}/include/pycairo".format(sys.exec_prefix)) - #extra_comp_args.extend(check_output(["pkg-config", '--cflags', 'pycairo']).strip().split(' ')) - #linkflags.extend(check_output(["pkg-config", '--libs', 'pycairo']).strip().split(' ')) - except: - raise Exception("Failed to find compiler options for pycairo") - -if sys.platform == 'darwin': - extra_comp_args.append('-mmacosx-version-min=10.11') - # silence warning coming from boost python macros which - # would is hard to silence via pragma - extra_comp_args.append('-Wno-parentheses-equality') - linkflags.append('-mmacosx-version-min=10.11') -else: - linkflags.append('-lrt') - linkflags.append('-Wl,-z,origin') - linkflags.append('-Wl,-rpath=$ORIGIN/lib') - -if os.environ.get("CC", False) == False: - os.environ["CC"] = check_output([mapnik_config, '--cxx']) -if os.environ.get("CXX", False) == False: - os.environ["CXX"] = check_output([mapnik_config, '--cxx']) - -setup( - name="mapnik", - version="4.0.0", - packages=['mapnik','mapnik.printing'], - author="Blake Thompson", - author_email="flippmoke@gmail.com", - description="Python bindings for Mapnik", - license="GNU LESSER GENERAL PUBLIC LICENSE", - keywords="mapnik mapbox mapping cartography", - url="http://mapnik.org/", - tests_require=[ - 'nose', - ], - package_data={ - 'mapnik': ['lib/*.*', 'lib/*/*/*', 'share/*/*'], - }, - test_suite='nose.collector', - cmdclass={ - 'whichboost': WhichBoostCommand, - }, - ext_modules=[ - Extension('mapnik._mapnik', [ - 'src/mapnik_color.cpp', - 'src/mapnik_coord.cpp', - 'src/mapnik_datasource.cpp', - 'src/mapnik_datasource_cache.cpp', - 'src/mapnik_envelope.cpp', - 'src/mapnik_expression.cpp', - 'src/mapnik_feature.cpp', - 'src/mapnik_featureset.cpp', - 'src/mapnik_font_engine.cpp', - 'src/mapnik_fontset.cpp', - 'src/mapnik_gamma_method.cpp', - 'src/mapnik_geometry.cpp', - 'src/mapnik_grid.cpp', - 'src/mapnik_grid_view.cpp', - 'src/mapnik_image.cpp', - 'src/mapnik_image_view.cpp', - 'src/mapnik_label_collision_detector.cpp', - 'src/mapnik_layer.cpp', - 'src/mapnik_logger.cpp', - 'src/mapnik_map.cpp', - 'src/mapnik_palette.cpp', - 'src/mapnik_parameters.cpp', - 'src/mapnik_proj_transform.cpp', - 'src/mapnik_projection.cpp', - 'src/mapnik_python.cpp', - 'src/mapnik_query.cpp', - 'src/mapnik_raster_colorizer.cpp', - 'src/mapnik_rule.cpp', - 'src/mapnik_scaling_method.cpp', - 'src/mapnik_style.cpp', - 'src/mapnik_symbolizer.cpp', - 'src/mapnik_view_transform.cpp', - 'src/python_grid_utils.cpp', - ], - language='c++', - extra_compile_args=extra_comp_args, - extra_link_args=linkflags, - ) - ] -) diff --git a/src/mapnik_enumeration.hpp b/src/mapnik_enumeration.hpp index 6e13abe55..663a1489c 100644 --- a/src/mapnik_enumeration.hpp +++ b/src/mapnik_enumeration.hpp @@ -68,7 +68,7 @@ class enumeration_ : using namespace boost::python::converter; return base_type::base::to_python( registered::converters.m_class_object - , static_cast( v )); + , static_cast(native_type(v))); } }; @@ -76,11 +76,9 @@ class enumeration_ : void init() { boost::python::implicitly_convertible(); boost::python::to_python_converter(); - - for (unsigned i = 0; i < EnumWrapper::MAX; ++i) + for (auto const& kv : EnumWrapper::lookupMap()) { - // Register the strings already defined for this enum. - base_type::value( EnumWrapper::get_string( i ), native_type( i ) ); + base_type::value(kv.second.c_str(), kv.first); } } diff --git a/src/mapnik_gamma_method.cpp b/src/mapnik_gamma_method.cpp index d0ba6f725..178da6175 100644 --- a/src/mapnik_gamma_method.cpp +++ b/src/mapnik_gamma_method.cpp @@ -36,11 +36,11 @@ void export_gamma_method() using namespace boost::python; mapnik::enumeration_("gamma_method") - .value("POWER", mapnik::GAMMA_POWER) - .value("LINEAR",mapnik::GAMMA_LINEAR) - .value("NONE", mapnik::GAMMA_NONE) - .value("THRESHOLD", mapnik::GAMMA_THRESHOLD) - .value("MULTIPLY", mapnik::GAMMA_MULTIPLY) + .value("POWER", mapnik::gamma_method_enum::GAMMA_POWER) + .value("LINEAR",mapnik::gamma_method_enum::GAMMA_LINEAR) + .value("NONE", mapnik::gamma_method_enum::GAMMA_NONE) + .value("THRESHOLD", mapnik::gamma_method_enum::GAMMA_THRESHOLD) + .value("MULTIPLY", mapnik::gamma_method_enum::GAMMA_MULTIPLY) ; } diff --git a/src/mapnik_raster_colorizer.cpp b/src/mapnik_raster_colorizer.cpp index 6a8a709b3..1dd524313 100644 --- a/src/mapnik_raster_colorizer.cpp +++ b/src/mapnik_raster_colorizer.cpp @@ -40,11 +40,6 @@ using mapnik::colorizer_stop; using mapnik::colorizer_stops; using mapnik::colorizer_mode_enum; using mapnik::color; -using mapnik::COLORIZER_INHERIT; -using mapnik::COLORIZER_LINEAR; -using mapnik::COLORIZER_DISCRETE; -using mapnik::COLORIZER_EXACT; - namespace { void add_stop(raster_colorizer_ptr & rc, colorizer_stop & stop) @@ -196,10 +191,10 @@ void export_raster_colorizer() ; enum_("ColorizerMode") - .value("COLORIZER_INHERIT", COLORIZER_INHERIT) - .value("COLORIZER_LINEAR", COLORIZER_LINEAR) - .value("COLORIZER_DISCRETE", COLORIZER_DISCRETE) - .value("COLORIZER_EXACT", COLORIZER_EXACT) + .value("COLORIZER_INHERIT", colorizer_mode_enum::COLORIZER_INHERIT) + .value("COLORIZER_LINEAR", colorizer_mode_enum::COLORIZER_LINEAR) + .value("COLORIZER_DISCRETE", colorizer_mode_enum::COLORIZER_DISCRETE) + .value("COLORIZER_EXACT", colorizer_mode_enum::COLORIZER_EXACT) .export_values() ; diff --git a/src/mapnik_style.cpp b/src/mapnik_style.cpp index 182943669..0353a472e 100644 --- a/src/mapnik_style.cpp +++ b/src/mapnik_style.cpp @@ -69,8 +69,8 @@ void export_style() using namespace boost::python; mapnik::enumeration_("filter_mode") - .value("ALL",mapnik::FILTER_ALL) - .value("FIRST",mapnik::FILTER_FIRST) + .value("ALL",mapnik::filter_mode_enum::FILTER_ALL) + .value("FIRST",mapnik::filter_mode_enum::FILTER_FIRST) ; class_("Rules",init<>("default ctor")) diff --git a/src/mapnik_symbolizer.cpp b/src/mapnik_symbolizer.cpp index ddbedf7e2..286b11af1 100644 --- a/src/mapnik_symbolizer.cpp +++ b/src/mapnik_symbolizer.cpp @@ -196,6 +196,17 @@ boost::python::object __getitem__(mapnik::symbolizer_base const& sym, std::strin return boost::python::object(); } +boost::python::object symbolizer_keys(mapnik::symbolizer_base const& sym) +{ + using const_iterator = symbolizer_base::cont_type::const_iterator; + boost::python::list keys; + for (auto const& kv : sym.properties) + { + std::string name = std::get<0>(mapnik::get_meta(kv.first)); + keys.append(name); + } + return keys; +} /* std::string __str__(mapnik::symbolizer const& sym) { @@ -268,6 +279,7 @@ void export_symbolizer() .def("__setattr__",&__setitem__) .def("__getitem__",&__getitem__) .def("__getattr__",&__getitem__) + .def("keys", &symbolizer_keys) //.def("__str__", &__str__) .def(self == self) // __eq__ ; @@ -277,38 +289,38 @@ void export_text_symbolizer() { using namespace boost::python; mapnik::enumeration_("label_placement") - .value("LINE_PLACEMENT", mapnik::LINE_PLACEMENT) - .value("POINT_PLACEMENT", mapnik::POINT_PLACEMENT) - .value("VERTEX_PLACEMENT", mapnik::VERTEX_PLACEMENT) - .value("INTERIOR_PLACEMENT", mapnik::INTERIOR_PLACEMENT); + .value("LINE_PLACEMENT", mapnik::label_placement_enum::LINE_PLACEMENT) + .value("POINT_PLACEMENT", mapnik::label_placement_enum::POINT_PLACEMENT) + .value("VERTEX_PLACEMENT", mapnik::label_placement_enum::VERTEX_PLACEMENT) + .value("INTERIOR_PLACEMENT", mapnik::label_placement_enum::INTERIOR_PLACEMENT); mapnik::enumeration_("vertical_alignment") - .value("TOP", mapnik::V_TOP) - .value("MIDDLE", mapnik::V_MIDDLE) - .value("BOTTOM", mapnik::V_BOTTOM) - .value("AUTO", mapnik::V_AUTO); + .value("TOP", mapnik::vertical_alignment_enum::V_TOP) + .value("MIDDLE", mapnik::vertical_alignment_enum::V_MIDDLE) + .value("BOTTOM", mapnik::vertical_alignment_enum::V_BOTTOM) + .value("AUTO", mapnik::vertical_alignment_enum::V_AUTO); mapnik::enumeration_("horizontal_alignment") - .value("LEFT", mapnik::H_LEFT) - .value("MIDDLE", mapnik::H_MIDDLE) - .value("RIGHT", mapnik::H_RIGHT) - .value("AUTO", mapnik::H_AUTO); + .value("LEFT", mapnik::horizontal_alignment_enum::H_LEFT) + .value("MIDDLE", mapnik::horizontal_alignment_enum::H_MIDDLE) + .value("RIGHT", mapnik::horizontal_alignment_enum::H_RIGHT) + .value("AUTO", mapnik::horizontal_alignment_enum::H_AUTO); mapnik::enumeration_("justify_alignment") - .value("LEFT", mapnik::J_LEFT) - .value("MIDDLE", mapnik::J_MIDDLE) - .value("RIGHT", mapnik::J_RIGHT) - .value("AUTO", mapnik::J_AUTO); + .value("LEFT", mapnik::justify_alignment_enum::J_LEFT) + .value("MIDDLE", mapnik::justify_alignment_enum::J_MIDDLE) + .value("RIGHT", mapnik::justify_alignment_enum::J_RIGHT) + .value("AUTO", mapnik::justify_alignment_enum::J_AUTO); mapnik::enumeration_("text_transform") - .value("NONE", mapnik::NONE) - .value("UPPERCASE", mapnik::UPPERCASE) - .value("LOWERCASE", mapnik::LOWERCASE) - .value("CAPITALIZE", mapnik::CAPITALIZE); + .value("NONE", mapnik::text_transform_enum::NONE) + .value("UPPERCASE", mapnik::text_transform_enum::UPPERCASE) + .value("LOWERCASE", mapnik::text_transform_enum::LOWERCASE) + .value("CAPITALIZE", mapnik::text_transform_enum::CAPITALIZE); mapnik::enumeration_("halo_rasterizer") - .value("FULL", mapnik::HALO_RASTERIZER_FULL) - .value("FAST", mapnik::HALO_RASTERIZER_FAST); + .value("FULL", mapnik::halo_rasterizer_enum::HALO_RASTERIZER_FULL) + .value("FAST", mapnik::halo_rasterizer_enum::HALO_RASTERIZER_FAST); class_< text_symbolizer, bases >("TextSymbolizer", init<>("Default ctor")) @@ -343,8 +355,8 @@ void export_polygon_pattern_symbolizer() using namespace boost::python; mapnik::enumeration_("pattern_alignment") - .value("LOCAL",mapnik::LOCAL_ALIGNMENT) - .value("GLOBAL",mapnik::GLOBAL_ALIGNMENT) + .value("LOCAL",mapnik::pattern_alignment_enum::LOCAL_ALIGNMENT) + .value("GLOBAL",mapnik::pattern_alignment_enum::GLOBAL_ALIGNMENT) ; class_("PolygonPatternSymbolizer", @@ -367,8 +379,8 @@ void export_point_symbolizer() using namespace boost::python; mapnik::enumeration_("point_placement") - .value("CENTROID",mapnik::CENTROID_POINT_PLACEMENT) - .value("INTERIOR",mapnik::INTERIOR_POINT_PLACEMENT) + .value("CENTROID",mapnik::point_placement_enum::CENTROID_POINT_PLACEMENT) + .value("INTERIOR",mapnik::point_placement_enum::INTERIOR_POINT_PLACEMENT) ; class_ >("PointSymbolizer", @@ -382,15 +394,15 @@ void export_markers_symbolizer() using namespace boost::python; mapnik::enumeration_("marker_placement") - .value("POINT_PLACEMENT",mapnik::MARKER_POINT_PLACEMENT) - .value("INTERIOR_PLACEMENT",mapnik::MARKER_INTERIOR_PLACEMENT) - .value("LINE_PLACEMENT",mapnik::MARKER_LINE_PLACEMENT) + .value("POINT_PLACEMENT",mapnik::marker_placement_enum::MARKER_POINT_PLACEMENT) + .value("INTERIOR_PLACEMENT",mapnik::marker_placement_enum::MARKER_INTERIOR_PLACEMENT) + .value("LINE_PLACEMENT",mapnik::marker_placement_enum::MARKER_LINE_PLACEMENT) ; mapnik::enumeration_("marker_multi_policy") - .value("EACH",mapnik::MARKER_EACH_MULTI) - .value("WHOLE",mapnik::MARKER_WHOLE_MULTI) - .value("LARGEST",mapnik::MARKER_LARGEST_MULTI) + .value("EACH",mapnik::marker_multi_policy_enum::MARKER_EACH_MULTI) + .value("WHOLE",mapnik::marker_multi_policy_enum::MARKER_WHOLE_MULTI) + .value("LARGEST",mapnik::marker_multi_policy_enum::MARKER_LARGEST_MULTI) ; class_ >("MarkersSymbolizer", @@ -405,25 +417,25 @@ void export_line_symbolizer() using namespace boost::python; mapnik::enumeration_("line_rasterizer") - .value("FULL",mapnik::RASTERIZER_FULL) - .value("FAST",mapnik::RASTERIZER_FAST) + .value("FULL",mapnik::line_rasterizer_enum::RASTERIZER_FULL) + .value("FAST",mapnik::line_rasterizer_enum::RASTERIZER_FAST) ; mapnik::enumeration_("stroke_linecap", "The possible values for a line cap used when drawing\n" "with a stroke.\n") - .value("BUTT_CAP",mapnik::BUTT_CAP) - .value("SQUARE_CAP",mapnik::SQUARE_CAP) - .value("ROUND_CAP",mapnik::ROUND_CAP) + .value("BUTT_CAP",mapnik::line_cap_enum::BUTT_CAP) + .value("SQUARE_CAP",mapnik::line_cap_enum::SQUARE_CAP) + .value("ROUND_CAP",mapnik::line_cap_enum::ROUND_CAP) ; mapnik::enumeration_("stroke_linejoin", "The possible values for the line joining mode\n" "when drawing with a stroke.\n") - .value("MITER_JOIN",mapnik::MITER_JOIN) - .value("MITER_REVERT_JOIN",mapnik::MITER_REVERT_JOIN) - .value("ROUND_JOIN",mapnik::ROUND_JOIN) - .value("BEVEL_JOIN",mapnik::BEVEL_JOIN) + .value("MITER_JOIN",mapnik::line_join_enum::MITER_JOIN) + .value("MITER_REVERT_JOIN",mapnik::line_join_enum::MITER_REVERT_JOIN) + .value("ROUND_JOIN",mapnik::line_join_enum::ROUND_JOIN) + .value("BEVEL_JOIN",mapnik::line_join_enum::BEVEL_JOIN) ; @@ -448,8 +460,8 @@ void export_debug_symbolizer() using namespace boost::python; mapnik::enumeration_("debug_symbolizer_mode") - .value("COLLISION",mapnik::DEBUG_SYM_MODE_COLLISION) - .value("VERTEX",mapnik::DEBUG_SYM_MODE_VERTEX) + .value("COLLISION",mapnik::debug_symbolizer_mode_enum::DEBUG_SYM_MODE_COLLISION) + .value("VERTEX",mapnik::debug_symbolizer_mode_enum::DEBUG_SYM_MODE_VERTEX) ; class_ >("DebugSymbolizer", diff --git a/test/python_tests/agg_rasterizer_integer_overflow_test.py b/test/python_tests/agg_rasterizer_integer_overflow_test.py index 1f984fb61..2a8c08571 100644 --- a/test/python_tests/agg_rasterizer_integer_overflow_test.py +++ b/test/python_tests/agg_rasterizer_integer_overflow_test.py @@ -1,14 +1,6 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - import json - -from nose.tools import eq_ - import mapnik -from .utilities import run_all - # geojson box of the world geojson = {"type": "Feature", "properties": {}, @@ -24,7 +16,6 @@ [-17963313.143242701888084, -6300857.11560364998877]]]}} - def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_memory(): expected_color = mapnik.Color('white') projection = 'epsg:4326' @@ -52,8 +43,7 @@ def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_memory(): # m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372)) im = mapnik.Image(256, 256) mapnik.render(m, im) - eq_(im.get_pixel(128, 128), expected_color.packed()) - + assert im.get_pixel(128, 128) == expected_color.packed() def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_csv(): expected_color = mapnik.Color('white') @@ -84,7 +74,4 @@ def test_that_coordinates_do_not_overflow_and_polygon_is_rendered_csv(): # m.zoom_to_box(mapnik.Box2d(-13658379.710221574,6195679.764683247,-13655933.72531645,6198125.749588372)) im = mapnik.Image(256, 256) mapnik.render(m, im) - eq_(im.get_pixel(128, 128), expected_color.packed()) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert im.get_pixel(128, 128) == expected_color.packed() diff --git a/test/python_tests/box2d_test.py b/test/python_tests/box2d_test.py index 7fe0a9f59..e3a477003 100644 --- a/test/python_tests/box2d_test.py +++ b/test/python_tests/box2d_test.py @@ -1,184 +1,155 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from nose.tools import assert_almost_equal, assert_false, assert_true, eq_ - import mapnik - -from .utilities import run_all - +import pytest def test_coord_init(): c = mapnik.Coord(100, 100) - - eq_(c.x, 100) - eq_(c.y, 100) - + assert c.x == 100 + assert c.y == 100 def test_coord_multiplication(): - c = mapnik.Coord(100, 100) - c *= 2 - - eq_(c.x, 200) - eq_(c.y, 200) - + c = mapnik.Coord(100, 100) + c *= 2 + assert c.x == 200 + assert c.y == 200 def test_envelope_init(): - e = mapnik.Box2d(100, 100, 200, 200) - - assert_true(e.contains(100, 100)) - assert_true(e.contains(100, 200)) - assert_true(e.contains(200, 200)) - assert_true(e.contains(200, 100)) - - assert_true(e.contains(e.center())) - - assert_false(e.contains(99.9, 99.9)) - assert_false(e.contains(99.9, 200.1)) - assert_false(e.contains(200.1, 200.1)) - assert_false(e.contains(200.1, 99.9)) - - eq_(e.width(), 100) - eq_(e.height(), 100) - - eq_(e.minx, 100) - eq_(e.miny, 100) - - eq_(e.maxx, 200) - eq_(e.maxy, 200) - - eq_(e[0], 100) - eq_(e[1], 100) - eq_(e[2], 200) - eq_(e[3], 200) - eq_(e[0], e[-4]) - eq_(e[1], e[-3]) - eq_(e[2], e[-2]) - eq_(e[3], e[-1]) - - c = e.center() - - eq_(c.x, 150) - eq_(c.y, 150) + e = mapnik.Box2d(100, 100, 200, 200) + assert e.contains(100, 100) + assert e.contains(100, 200) + assert e.contains(200, 200) + assert e.contains(200, 100) + assert e.contains(e.center()) + assert not e.contains(99.9, 99.9) + assert not e.contains(99.9, 200.1) + assert not e.contains(200.1, 200.1) + assert not e.contains(200.1, 99.9) + assert e.width() == 100 + assert e.height() == 100 + assert e.minx == 100 + assert e.miny == 100 + assert e.maxx == 200 + assert e.maxy == 200 + assert e[0] == 100 + assert e[1] == 100 + assert e[2] == 200 + assert e[3] == 200 + assert e[0] == e[-4] + assert e[1] == e[-3] + assert e[2] == e[-2] + assert e[3] == e[-1] + c = e.center() + assert c.x == 150 + assert c.y == 150 def test_envelope_static_init(): e = mapnik.Box2d.from_string('100 100 200 200') e2 = mapnik.Box2d.from_string('100,100,200,200') e3 = mapnik.Box2d.from_string('100 , 100 , 200 , 200') - eq_(e, e2) - eq_(e, e3) - - assert_true(e.contains(100, 100)) - assert_true(e.contains(100, 200)) - assert_true(e.contains(200, 200)) - assert_true(e.contains(200, 100)) - - assert_true(e.contains(e.center())) - - assert_false(e.contains(99.9, 99.9)) - assert_false(e.contains(99.9, 200.1)) - assert_false(e.contains(200.1, 200.1)) - assert_false(e.contains(200.1, 99.9)) - - eq_(e.width(), 100) - eq_(e.height(), 100) - eq_(e.minx, 100) - eq_(e.miny, 100) - - eq_(e.maxx, 200) - eq_(e.maxy, 200) - - eq_(e[0], 100) - eq_(e[1], 100) - eq_(e[2], 200) - eq_(e[3], 200) - eq_(e[0], e[-4]) - eq_(e[1], e[-3]) - eq_(e[2], e[-2]) - eq_(e[3], e[-1]) + assert e == e2 + assert e == e3 + assert e.contains(100, 100) + assert e.contains(100, 200) + assert e.contains(200, 200) + assert e.contains(200, 100) + + assert e.contains(e.center()) + assert not e.contains(99.9, 99.9) + assert not e.contains(99.9, 200.1) + assert not e.contains(200.1, 200.1) + assert not e.contains(200.1, 99.9) + + assert e.width() == 100 + assert e.height() == 100 + assert e.minx == 100 + assert e.miny == 100 + assert e.maxx == 200 + assert e.maxy == 200 + + assert e[0] == 100 + assert e[1] == 100 + assert e[2] == 200 + assert e[3] == 200 + assert e[0] == e[-4] + assert e[1] == e[-3] + assert e[2] == e[-2] + assert e[3] == e[-1] c = e.center() - - eq_(c.x, 150) - eq_(c.y, 150) - + assert c.x == 150 + assert c.y == 150 def test_envelope_multiplication(): - # no width then no impact of multiplication - a = mapnik.Box2d(100, 100, 100, 100) - a *= 5 - eq_(a.minx, 100) - eq_(a.miny, 100) - eq_(a.maxx, 100) - eq_(a.maxy, 100) - - a = mapnik.Box2d(100.0, 100.0, 100.0, 100.0) - a *= 5 - eq_(a.minx, 100) - eq_(a.miny, 100) - eq_(a.maxx, 100) - eq_(a.maxy, 100) - - a = mapnik.Box2d(100.0, 100.0, 100.001, 100.001) - a *= 5 - assert_almost_equal(a.minx, 99.9979, places=3) - assert_almost_equal(a.miny, 99.9979, places=3) - assert_almost_equal(a.maxx, 100.0030, places=3) - assert_almost_equal(a.maxy, 100.0030, places=3) - - e = mapnik.Box2d(100, 100, 200, 200) - e *= 2 - eq_(e.minx, 50) - eq_(e.miny, 50) - eq_(e.maxx, 250) - eq_(e.maxy, 250) - - assert_true(e.contains(50, 50)) - assert_true(e.contains(50, 250)) - assert_true(e.contains(250, 250)) - assert_true(e.contains(250, 50)) - - assert_false(e.contains(49.9, 49.9)) - assert_false(e.contains(49.9, 250.1)) - assert_false(e.contains(250.1, 250.1)) - assert_false(e.contains(250.1, 49.9)) - - assert_true(e.contains(e.center())) - - eq_(e.width(), 200) - eq_(e.height(), 200) - - eq_(e.minx, 50) - eq_(e.miny, 50) - - eq_(e.maxx, 250) - eq_(e.maxy, 250) - - c = e.center() - - eq_(c.x, 150) - eq_(c.y, 150) + # no width then no impact of multiplication + a = mapnik.Box2d(100, 100, 100, 100) + a *= 5 + assert a.minx == 100 + assert a.miny == 100 + assert a.maxx == 100 + assert a.maxy == 100 + + a = mapnik.Box2d(100.0, 100.0, 100.0, 100.0) + a *= 5 + assert a.minx == 100 + assert a.miny == 100 + assert a.maxx == 100 + assert a.maxy == 100 + + a = mapnik.Box2d(100.0, 100.0, 100.001, 100.001) + a *= 5 + assert a.minx == pytest.approx(99.9979, 1e-3) + assert a.miny == pytest.approx(99.9979, 1e-3) + assert a.maxx == pytest.approx(100.0030,1e-3) + assert a.maxy == pytest.approx(100.0030,1e-3) + + e = mapnik.Box2d(100, 100, 200, 200) + e *= 2 + assert e.minx == 50 + assert e.miny == 50 + assert e.maxx == 250 + assert e.maxy == 250 + + assert e.contains(50, 50) + assert e.contains(50, 250) + assert e.contains(250, 250) + assert e.contains(250, 50) + + assert not e.contains(49.9, 49.9) + assert not e.contains(49.9, 250.1) + assert not e.contains(250.1, 250.1) + assert not e.contains(250.1, 49.9) + + c = e.center() + assert c.x == 150 + assert c.y == 150 + + assert e.contains(c) + + assert e.width() == 200 + assert e.height()== 200 + + assert e.minx == 50 + assert e.miny == 50 + + assert e.maxx == 250 + assert e.maxy == 250 def test_envelope_clipping(): - e1 = mapnik.Box2d(-180, -90, 180, 90) - e2 = mapnik.Box2d(-120, 40, -110, 48) - e1.clip(e2) - eq_(e1, e2) - - # madagascar in merc - e1 = mapnik.Box2d(4772116.5490, -2744395.0631, 5765186.4203, -1609458.0673) - e2 = mapnik.Box2d(5124338.3753, -2240522.1727, 5207501.8621, -2130452.8520) - e1.clip(e2) - eq_(e1, e2) - - # nz in lon/lat - e1 = mapnik.Box2d(163.8062, -47.1897, 179.3628, -33.9069) - e2 = mapnik.Box2d(173.7378, -39.6395, 174.4849, -38.9252) - e1.clip(e2) - eq_(e1, e2) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + e1 = mapnik.Box2d(-180, -90, 180, 90) + e2 = mapnik.Box2d(-120, 40, -110, 48) + e1.clip(e2) + assert e1 == e2 + + # madagascar in merc + e1 = mapnik.Box2d(4772116.5490, -2744395.0631, 5765186.4203, -1609458.0673) + e2 = mapnik.Box2d(5124338.3753, -2240522.1727, 5207501.8621, -2130452.8520) + e1.clip(e2) + assert e1 == e2 + +# # nz in lon/lat + e1 = mapnik.Box2d(163.8062, -47.1897, 179.3628, -33.9069) + e2 = mapnik.Box2d(173.7378, -39.6395, 174.4849, -38.9252) + e1.clip(e2) + assert e1 == e2 diff --git a/test/python_tests/buffer_clear_test.py b/test/python_tests/buffer_clear_test.py index b94e9e4c6..74b0ee13a 100644 --- a/test/python_tests/buffer_clear_test.py +++ b/test/python_tests/buffer_clear_test.py @@ -1,30 +1,17 @@ import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_clearing_image_data(): im = mapnik.Image(256, 256) # make sure it equals itself bytes = im.tostring() - eq_(im.tostring(), bytes) + assert im.tostring() == bytes # set background, then clear im.fill(mapnik.Color('green')) - eq_(im.tostring() != bytes, True) + assert not im.tostring() == bytes # clear image, should now equal original im.clear() - eq_(im.tostring(), bytes) - + assert im.tostring() == bytes def make_map(): ds = mapnik.MemoryDatasource() @@ -56,14 +43,10 @@ def test_clearing_grid_data(): g = mapnik.Grid(256, 256) utf = g.encode() # make sure it equals itself - eq_(g.encode(), utf) + assert g.encode() == utf m = make_map() mapnik.render_layer(m, g, layer=0, fields=['__id__', 'Name']) - eq_(g.encode() != utf, True) + assert g.encode() != utf # clear grid, should now match original g.clear() - eq_(g.encode(), utf) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert g.encode() == utf diff --git a/test/python_tests/cairo_test.py b/test/python_tests/cairo_test.py index c6c25a379..a296a91a2 100644 --- a/test/python_tests/cairo_test.py +++ b/test/python_tests/cairo_test.py @@ -1,23 +1,7 @@ -#!/usr/bin/env python - -from __future__ import print_function - import os import shutil - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def make_tmp_map(): m = mapnik.Map(512, 512) m.background_color = mapnik.Color('steelblue') @@ -41,13 +25,12 @@ def make_tmp_map(): m.layers.append(lyr) return m - def draw_title(m, ctx, text, size=10, color=mapnik.Color('black')): """ Draw a Map Title near the top of a page.""" middle = m.width / 2.0 ctx.set_source_rgba(*cairo_color(color)) ctx.select_font_face( - "DejaVu Sans Book", + "Helvetica", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.set_font_size(size) @@ -97,7 +80,7 @@ def test_passing_pycairo_context_svg(): m.zoom_to_box(mapnik.Box2d(-180, -90, 180, 90)) test_cairo_file = '/tmp/mapnik-cairo-context-test.svg' surface = cairo.SVGSurface(test_cairo_file, m.width, m.height) - expected_cairo_file = './images/pycairo/cairo-cairo-expected.svg' + expected_cairo_file = './test/python_tests/images/pycairo/cairo-cairo-expected.svg' context = cairo.Context(surface) mapnik.render(m, context) draw_title(m, context, "Hello Map", size=20) @@ -111,7 +94,7 @@ def test_passing_pycairo_context_svg(): os.stat(test_cairo_file).st_size) msg = 'diff in size (%s) between actual (%s) and expected(%s)' % ( diff, test_cairo_file, 'tests/python_tests/' + expected_cairo_file) - eq_(diff < 1500, True, msg) + assert diff < 1500, msg os.remove(test_cairo_file) def test_passing_pycairo_context_pdf(): @@ -119,7 +102,7 @@ def test_passing_pycairo_context_pdf(): m.zoom_to_box(mapnik.Box2d(-180, -90, 180, 90)) test_cairo_file = '/tmp/mapnik-cairo-context-test.pdf' surface = cairo.PDFSurface(test_cairo_file, m.width, m.height) - expected_cairo_file = './images/pycairo/cairo-cairo-expected.pdf' + expected_cairo_file = './test/python_tests/images/pycairo/cairo-cairo-expected.pdf' context = cairo.Context(surface) mapnik.render(m, context) draw_title(m, context, "Hello Map", size=20) @@ -133,7 +116,7 @@ def test_passing_pycairo_context_pdf(): os.stat(test_cairo_file).st_size) msg = 'diff in size (%s) between actual (%s) and expected(%s)' % ( diff, test_cairo_file, 'tests/python_tests/' + expected_cairo_file) - eq_(diff < 1500, True, msg) + assert diff < 1500, msg os.remove(test_cairo_file) def test_passing_pycairo_context_png(): @@ -141,8 +124,8 @@ def test_passing_pycairo_context_png(): m.zoom_to_box(mapnik.Box2d(-180, -90, 180, 90)) test_cairo_file = '/tmp/mapnik-cairo-context-test.png' surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, m.width, m.height) - expected_cairo_file = './images/pycairo/cairo-cairo-expected.png' - expected_cairo_file2 = './images/pycairo/cairo-cairo-expected-reduced.png' + expected_cairo_file = './test/python_tests/images/pycairo/cairo-cairo-expected.png' + expected_cairo_file2 = './test/python_tests/images/pycairo/cairo-cairo-expected-reduced.png' context = cairo.Context(surface) mapnik.render(m, context) draw_title(m, context, "Hello Map", size=20) @@ -160,7 +143,7 @@ def test_passing_pycairo_context_png(): os.stat(test_cairo_file).st_size) msg = 'diff in size (%s) between actual (%s) and expected(%s)' % ( diff, test_cairo_file, 'tests/python_tests/' + expected_cairo_file) - eq_(diff < 500, True, msg) + assert diff < 500, msg os.remove(test_cairo_file) if not os.path.exists( expected_cairo_file2) or os.environ.get('UPDATE'): @@ -173,17 +156,17 @@ def test_passing_pycairo_context_png(): os.stat(reduced_color_image).st_size) msg = 'diff in size (%s) between actual (%s) and expected(%s)' % ( diff, reduced_color_image, 'tests/python_tests/' + expected_cairo_file2) - eq_(diff < 500, True, msg) + assert diff < 500, msg os.remove(reduced_color_image) if 'sqlite' in mapnik.DatasourceCache.plugin_names(): def _pycairo_surface(type, sym): test_cairo_file = '/tmp/mapnik-cairo-surface-test.%s.%s' % ( sym, type) - expected_cairo_file = './images/pycairo/cairo-surface-expected.%s.%s' % ( + expected_cairo_file = './test/python_tests/images/pycairo/cairo-surface-expected.%s.%s' % ( sym, type) m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/%s_symbolizer.xml' % sym) + mapnik.load_map(m, './test/data/good_maps/%s_symbolizer.xml' % sym) m.zoom_all() if hasattr(cairo, '%sSurface' % type.upper()): surface = getattr( @@ -207,9 +190,9 @@ def _pycairo_surface(type, sym): msg = 'diff in size (%s) between actual (%s) and expected(%s)' % ( diff, test_cairo_file, 'tests/python_tests/' + expected_cairo_file) if os.uname()[0] == 'Darwin': - eq_(diff < 2100, True, msg) + assert diff < 2100, msg else: - eq_(diff < 23000, True, msg) + assert diff < 23000, msg os.remove(test_cairo_file) return True else: @@ -219,23 +202,19 @@ def _pycairo_surface(type, sym): return True def test_pycairo_svg_surface1(): - eq_(_pycairo_surface('svg', 'point'), True) + assert _pycairo_surface('svg', 'point') def test_pycairo_svg_surface2(): - eq_(_pycairo_surface('svg', 'building'), True) + assert _pycairo_surface('svg', 'building') def test_pycairo_svg_surface3(): - eq_(_pycairo_surface('svg', 'polygon'), True) + assert _pycairo_surface('svg', 'polygon') def test_pycairo_pdf_surface1(): - eq_(_pycairo_surface('pdf', 'point'), True) + assert _pycairo_surface('pdf', 'point') def test_pycairo_pdf_surface2(): - eq_(_pycairo_surface('pdf', 'building'), True) + assert _pycairo_surface('pdf', 'building') def test_pycairo_pdf_surface3(): - eq_(_pycairo_surface('pdf', 'polygon'), True) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert _pycairo_surface('pdf', 'polygon') diff --git a/test/python_tests/color_test.py b/test/python_tests/color_test.py index 428843145..e8fc90fc6 100644 --- a/test/python_tests/color_test.py +++ b/test/python_tests/color_test.py @@ -1,121 +1,102 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_color_init(): c = mapnik.Color(12, 128, 255) - eq_(c.r, 12) - eq_(c.g, 128) - eq_(c.b, 255) - eq_(c.a, 255) - eq_(False, c.get_premultiplied()) + assert c.r == 12 + assert c.g == 128 + assert c.b == 255 + assert c.a == 255 + assert not c.get_premultiplied() c = mapnik.Color(16, 32, 64, 128) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(False, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert not c.get_premultiplied() c = mapnik.Color(16, 32, 64, 128, True) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(True, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert c.get_premultiplied() c = mapnik.Color('rgba(16,32,64,0.5)') - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(False, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert not c.get_premultiplied() c = mapnik.Color('rgba(16,32,64,0.5)', True) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(True, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert c.get_premultiplied() hex_str = '#10204080' c = mapnik.Color(hex_str) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(hex_str, c.to_hex_string()) - eq_(False, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert hex_str == c.to_hex_string() + assert not c.get_premultiplied() c = mapnik.Color(hex_str, True) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(hex_str, c.to_hex_string()) - eq_(True, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert hex_str == c.to_hex_string() + assert c.get_premultiplied() rgba_int = 2151686160 c = mapnik.Color(rgba_int) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(rgba_int, c.packed()) - eq_(False, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert rgba_int == c.packed() + assert not c.get_premultiplied() c = mapnik.Color(rgba_int, True) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) - eq_(rgba_int, c.packed()) - eq_(True, c.get_premultiplied()) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 + assert rgba_int == c.packed() + assert c.get_premultiplied() def test_color_properties(): c = mapnik.Color(16, 32, 64, 128) - eq_(c.r, 16) - eq_(c.g, 32) - eq_(c.b, 64) - eq_(c.a, 128) + assert c.r == 16 + assert c.g == 32 + assert c.b == 64 + assert c.a == 128 c.r = 17 - eq_(c.r, 17) + assert c.r == 17 c.g = 33 - eq_(c.g, 33) + assert c.g == 33 c.b = 65 - eq_(c.b, 65) + assert c.b == 65 c.a = 128 - eq_(c.a, 128) + assert c.a == 128 def test_color_premultiply(): c = mapnik.Color(16, 33, 255, 128) - eq_(c.premultiply(), True) - eq_(c.r, 8) - eq_(c.g, 17) - eq_(c.b, 128) - eq_(c.a, 128) + assert c.premultiply() + assert c.r == 8 + assert c.g == 17 + assert c.b == 128 + assert c.a == 128 # Repeating it again should do nothing - eq_(c.premultiply(), False) - eq_(c.r, 8) - eq_(c.g, 17) - eq_(c.b, 128) - eq_(c.a, 128) + assert not c.premultiply() + assert c.r == 8 + assert c.g == 17 + assert c.b == 128 + assert c.a == 128 c.demultiply() c.demultiply() # This will not return the same values as before but we expect that - eq_(c.r, 15) - eq_(c.g, 33) - eq_(c.b, 255) - eq_(c.a, 128) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert c.r == 15 + assert c.g == 33 + assert c.b == 255 + assert c.a == 128 diff --git a/test/python_tests/compare_test.py b/test/python_tests/compare_test.py index bb8397a2b..b66775262 100644 --- a/test/python_tests/compare_test.py +++ b/test/python_tests/compare_test.py @@ -1,48 +1,32 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_another_compare(): im = mapnik.Image(5, 5) im2 = mapnik.Image(5, 5) im2.fill(mapnik.Color('rgba(255,255,255,0)')) - eq_(im.compare(im2, 16), im.width() * im.height()) - + assert im.compare(im2, 16) == im.width() * im.height() def test_compare_rgba8(): im = mapnik.Image(5, 5, mapnik.ImageType.rgba8) im.fill(mapnik.Color(0, 0, 0, 0)) - eq_(im.compare(im), 0) + assert im.compare(im) == 0 im2 = mapnik.Image(5, 5, mapnik.ImageType.rgba8) im2.fill(mapnik.Color(0, 0, 0, 0)) - eq_(im.compare(im2), 0) - eq_(im2.compare(im), 0) + assert im.compare(im2) == 0 + assert im2.compare(im) == 0 im2.fill(mapnik.Color(0, 0, 0, 12)) - eq_(im.compare(im2), 25) - eq_(im.compare(im2, 0, False), 0) + assert im.compare(im2) == 25 + assert im.compare(im2, 0, False) == 0 im3 = mapnik.Image(5, 5, mapnik.ImageType.rgba8) im3.set_pixel(0, 0, mapnik.Color(0, 0, 0, 0)) im3.set_pixel(0, 1, mapnik.Color(1, 1, 1, 1)) im3.set_pixel(1, 0, mapnik.Color(2, 2, 2, 2)) im3.set_pixel(1, 1, mapnik.Color(3, 3, 3, 3)) - eq_(im.compare(im3), 3) - eq_(im.compare(im3, 1), 2) - eq_(im.compare(im3, 2), 1) - eq_(im.compare(im3, 3), 0) + assert im.compare(im3) == 3 + assert im.compare(im3, 1) == 2 + assert im.compare(im3, 2) == 1 + assert im.compare(im3, 3) == 0 def test_compare_2_image(): @@ -50,75 +34,71 @@ def test_compare_2_image(): im.set_pixel(0, 0, mapnik.Color(254, 254, 254, 254)) im.set_pixel(4, 4, mapnik.Color('white')) im2 = mapnik.Image(5, 5) - eq_(im2.compare(im, 16), 2) + assert im2.compare(im, 16) == 2 def test_compare_dimensions(): im = mapnik.Image(2, 2) im2 = mapnik.Image(3, 3) - eq_(im.compare(im2), 4) - eq_(im2.compare(im), 9) + assert im.compare(im2) == 4 + assert im2.compare(im) == 9 def test_compare_gray8(): im = mapnik.Image(2, 2, mapnik.ImageType.gray8) im.fill(0) - eq_(im.compare(im), 0) + assert im.compare(im) == 0 im2 = mapnik.Image(2, 2, mapnik.ImageType.gray8) im2.fill(0) - eq_(im.compare(im2), 0) - eq_(im2.compare(im), 0) - eq_(im.compare(im2, 0, False), 0) + assert im.compare(im2) == 0 + assert im2.compare(im) == 0 + assert im.compare(im2, 0, False) == 0 im3 = mapnik.Image(2, 2, mapnik.ImageType.gray8) im3.set_pixel(0, 0, 0) im3.set_pixel(0, 1, 1) im3.set_pixel(1, 0, 2) im3.set_pixel(1, 1, 3) - eq_(im.compare(im3), 3) - eq_(im.compare(im3, 1), 2) - eq_(im.compare(im3, 2), 1) - eq_(im.compare(im3, 3), 0) + assert im.compare(im3) == 3 + assert im.compare(im3, 1) == 2 + assert im.compare(im3, 2) == 1 + assert im.compare(im3, 3) == 0 def test_compare_gray16(): im = mapnik.Image(2, 2, mapnik.ImageType.gray16) im.fill(0) - eq_(im.compare(im), 0) + assert im.compare(im) == 0 im2 = mapnik.Image(2, 2, mapnik.ImageType.gray16) im2.fill(0) - eq_(im.compare(im2), 0) - eq_(im2.compare(im), 0) - eq_(im.compare(im2, 0, False), 0) + assert im.compare(im2) == 0 + assert im2.compare(im) == 0 + assert im.compare(im2, 0, False) == 0 im3 = mapnik.Image(2, 2, mapnik.ImageType.gray16) im3.set_pixel(0, 0, 0) im3.set_pixel(0, 1, 1) im3.set_pixel(1, 0, 2) im3.set_pixel(1, 1, 3) - eq_(im.compare(im3), 3) - eq_(im.compare(im3, 1), 2) - eq_(im.compare(im3, 2), 1) - eq_(im.compare(im3, 3), 0) + assert im.compare(im3) == 3 + assert im.compare(im3, 1) == 2 + assert im.compare(im3, 2) == 1 + assert im.compare(im3, 3) == 0 def test_compare_gray32f(): im = mapnik.Image(2, 2, mapnik.ImageType.gray32f) im.fill(0.5) - eq_(im.compare(im), 0) + assert im.compare(im) == 0 im2 = mapnik.Image(2, 2, mapnik.ImageType.gray32f) im2.fill(0.5) - eq_(im.compare(im2), 0) - eq_(im2.compare(im), 0) - eq_(im.compare(im2, 0, False), 0) + assert im.compare(im2) == 0 + assert im2.compare(im) == 0 + assert im.compare(im2, 0, False) == 0 im3 = mapnik.Image(2, 2, mapnik.ImageType.gray32f) im3.set_pixel(0, 0, 0.5) im3.set_pixel(0, 1, 1.5) im3.set_pixel(1, 0, 2.5) im3.set_pixel(1, 1, 3.5) - eq_(im.compare(im3), 3) - eq_(im.compare(im3, 1.0), 2) - eq_(im.compare(im3, 2.0), 1) - eq_(im.compare(im3, 3.0), 0) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert im.compare(im3) == 3 + assert im.compare(im3, 1.0) == 2 + assert im.compare(im3, 2.0) == 1 + assert im.compare(im3, 3.0) == 0 diff --git a/test/python_tests/copy_test.py b/test/python_tests/copy_test.py index b4aa45db2..d08a21d0a 100644 --- a/test/python_tests/copy_test.py +++ b/test/python_tests/copy_test.py @@ -1,21 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_image_16_8_simple(): im = mapnik.Image(2, 2, mapnik.ImageType.gray16) im.set_pixel(0, 0, 256) @@ -23,16 +7,16 @@ def test_image_16_8_simple(): im.set_pixel(1, 0, 5) im.set_pixel(1, 1, 2) im2 = im.copy(mapnik.ImageType.gray8) - eq_(im2.get_pixel(0, 0), 255) - eq_(im2.get_pixel(0, 1), 255) - eq_(im2.get_pixel(1, 0), 5) - eq_(im2.get_pixel(1, 1), 2) + assert im2.get_pixel(0, 0) == 255 + assert im2.get_pixel(0, 1) == 255 + assert im2.get_pixel(1, 0) == 5 + assert im2.get_pixel(1, 1) == 2 # Cast back! im = im2.copy(mapnik.ImageType.gray16) - eq_(im.get_pixel(0, 0), 255) - eq_(im.get_pixel(0, 1), 255) - eq_(im.get_pixel(1, 0), 5) - eq_(im.get_pixel(1, 1), 2) + assert im.get_pixel(0, 0) == 255 + assert im.get_pixel(0, 1) == 255 + assert im.get_pixel(1, 0) == 5 + assert im.get_pixel(1, 1) == 2 def test_image_32f_8_simple(): @@ -42,20 +26,20 @@ def test_image_32f_8_simple(): im.set_pixel(1, 0, 120.6) im.set_pixel(1, 1, 360.2) im2 = im.copy(mapnik.ImageType.gray8) - eq_(im2.get_pixel(0, 0), 120) - eq_(im2.get_pixel(0, 1), 0) - eq_(im2.get_pixel(1, 0), 120) # Notice this is truncated! - eq_(im2.get_pixel(1, 1), 255) + assert im2.get_pixel(0, 0) == 120 + assert im2.get_pixel(0, 1) == 0 + assert im2.get_pixel(1, 0) == 120 # Notice this is truncated! + assert im2.get_pixel(1, 1) == 255 def test_image_offset_and_scale(): im = mapnik.Image(2, 2, mapnik.ImageType.gray16) - eq_(im.offset, 0.0) - eq_(im.scaling, 1.0) + assert im.offset == 0.0 + assert im.scaling == 1.0 im.offset = 1.0 im.scaling = 2.0 - eq_(im.offset, 1.0) - eq_(im.scaling, 2.0) + assert im.offset == 1.0 + assert im.scaling == 2.0 def test_image_16_8_scale_and_offset(): @@ -67,17 +51,17 @@ def test_image_16_8_scale_and_offset(): offset = 255 scaling = 3 im2 = im.copy(mapnik.ImageType.gray8, offset, scaling) - eq_(im2.get_pixel(0, 0), 0) - eq_(im2.get_pixel(0, 1), 1) - eq_(im2.get_pixel(1, 0), 255) - eq_(im2.get_pixel(1, 1), 120) + assert im2.get_pixel(0, 0) == 0 + assert im2.get_pixel(0, 1) == 1 + assert im2.get_pixel(1, 0) == 255 + assert im2.get_pixel(1, 1) == 120 # pixels will be a little off due to offsets in reverting! im3 = im2.copy(mapnik.ImageType.gray16) - eq_(im3.get_pixel(0, 0), 255) # Rounding error with ints - eq_(im3.get_pixel(0, 1), 258) # same + assert im3.get_pixel(0, 0) == 255 # Rounding error with ints + assert im3.get_pixel(0, 1) == 258 # same # The other one was way out of range for our scale/offset - eq_(im3.get_pixel(1, 0), 1020) - eq_(im3.get_pixel(1, 1), 615) # same + assert im3.get_pixel(1, 0) == 1020 + assert im3.get_pixel(1, 1) == 615 # same def test_image_16_32f_scale_and_offset(): @@ -89,16 +73,12 @@ def test_image_16_32f_scale_and_offset(): offset = 255 scaling = 3.2 im2 = im.copy(mapnik.ImageType.gray32f, offset, scaling) - eq_(im2.get_pixel(0, 0), 0.3125) - eq_(im2.get_pixel(0, 1), 0.9375) - eq_(im2.get_pixel(1, 0), -79.6875) - eq_(im2.get_pixel(1, 1), 112.5) + assert im2.get_pixel(0, 0) == 0.3125 + assert im2.get_pixel(0, 1) == 0.9375 + assert im2.get_pixel(1, 0) == -79.6875 + assert im2.get_pixel(1, 1) == 112.5 im3 = im2.copy(mapnik.ImageType.gray16) - eq_(im3.get_pixel(0, 0), 256) - eq_(im3.get_pixel(0, 1), 258) - eq_(im3.get_pixel(1, 0), 0) - eq_(im3.get_pixel(1, 1), 615) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert im3.get_pixel(0, 0) == 256 + assert im3.get_pixel(0, 1) == 258 + assert im3.get_pixel(1, 0) == 0 + assert im3.get_pixel(1, 1) == 615 diff --git a/test/python_tests/csv_test.py b/test/python_tests/csv_test.py index 5f131b3d3..07c681cfa 100644 --- a/test/python_tests/csv_test.py +++ b/test/python_tests/csv_test.py @@ -1,45 +1,20 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from __future__ import print_function - import glob import os - -from nose.tools import eq_, raises - import mapnik - -from .utilities import execution_path - - -default_logging_severity = mapnik.logger.get_severity() - - -def setup(): - # make the tests silent since we intentially test error conditions that - # are noisy - mapnik.logger.set_severity(getattr(mapnik.severity_type, "None")) - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - -def teardown(): - mapnik.logger.set_severity(default_logging_severity) +import pytest if 'csv' in mapnik.DatasourceCache.plugin_names(): def get_csv_ds(filename): return mapnik.Datasource( - type='csv', file=os.path.join('../data/csv/', filename)) + type='csv', file=os.path.join('./test/data/csv/', filename)) def test_broken_files(visual=False): - broken = glob.glob("../data/csv/fails/*.*") - broken.extend(glob.glob("../data/csv/warns/*.*")) + broken = glob.glob("./test/data/csv/fails/*.*") + broken.extend(glob.glob("./test/data/csv/warns/*.*")) # Add a filename that doesn't exist - broken.append("../data/csv/fails/does_not_exist.csv") + broken.append("./test/data/csv/fails/does_not_exist.csv") for csv in broken: if visual: @@ -50,9 +25,10 @@ def test_broken_files(visual=False): print('\x1b[1;32m✓ \x1b[0m', csv) def test_good_files(visual=False): - good_files = glob.glob("../data/csv/*.*") - good_files.extend(glob.glob("../data/csv/warns/*.*")) - ignorable = os.path.join('..', 'data', 'csv', 'long_lat.vrt') + good_files = glob.glob("./test/data/csv/*.*") + good_files.extend(glob.glob("./test/data/csv/warns/*.*")) + ignorable = os.path.join('./test', 'data', 'csv', 'long_lat.vrt') + print("ignorable:", ignorable) good_files.remove(ignorable) for f in good_files: if f.endswith('.index'): @@ -70,46 +46,45 @@ def test_good_files(visual=False): def test_lon_lat_detection(**kwargs): ds = get_csv_ds('lon_lat.csv') - eq_(len(ds.fields()), 2) - eq_(ds.fields(), ['lon', 'lat']) - eq_(ds.field_types(), ['int', 'int']) + assert len(ds.fields()) == 2 + assert ds.fields(), ['lon' == 'lat'] + assert ds.field_types(), ['int' == 'int'] query = mapnik.Query(ds.envelope()) for fld in ds.fields(): query.add_property_name(fld) fs = ds.features(query) desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point feat = fs.next() attr = {'lon': 0, 'lat': 0} - eq_(feat.attributes, attr) + assert feat.attributes == attr def test_lng_lat_detection(**kwargs): ds = get_csv_ds('lng_lat.csv') - eq_(len(ds.fields()), 2) - eq_(ds.fields(), ['lng', 'lat']) - eq_(ds.field_types(), ['int', 'int']) + assert len(ds.fields()) == 2 + assert ds.fields(), ['lng' == 'lat'] + assert ds.field_types(), ['int' == 'int'] query = mapnik.Query(ds.envelope()) for fld in ds.fields(): query.add_property_name(fld) fs = ds.features(query) desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point feat = fs.next() attr = {'lng': 0, 'lat': 0} - eq_(feat.attributes, attr) + assert feat.attributes == attr def test_type_detection(**kwargs): ds = get_csv_ds('nypd.csv') - eq_(ds.fields(), - ['Precinct', - 'Phone', - 'Address', - 'City', - 'geo_longitude', - 'geo_latitude', - 'geo_accuracy']) - eq_(ds.field_types(), ['str', 'str', - 'str', 'str', 'float', 'float', 'str']) + assert ds.fields() == ['Precinct', + 'Phone', + 'Address', + 'City', + 'geo_longitude', + 'geo_latitude', + 'geo_accuracy'] + assert ds.field_types() == ['str', 'str', + 'str', 'str', 'float', 'float', 'str'] feat = ds.featureset().next() attr = { 'City': u'New York, NY', @@ -119,33 +94,33 @@ def test_type_detection(**kwargs): 'Precinct': u'5th Precinct', 'geo_longitude': -70, 'geo_latitude': 40} - eq_(feat.attributes, attr) - eq_(len(list(ds.all_features())), 2) + assert feat.attributes == attr + assert len(list(ds.all_features())) == 2 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_skipping_blank_rows(**kwargs): ds = get_csv_ds('blank_rows.csv') - eq_(ds.fields(), ['x', 'y', 'name']) - eq_(ds.field_types(), ['int', 'int', 'str']) - eq_(len(list(ds.all_features())), 2) + assert ds.fields(), ['x', 'y' == 'name'] + assert ds.field_types(), ['int', 'int' == 'str'] + assert len(list(ds.all_features())) == 2 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_empty_rows(**kwargs): ds = get_csv_ds('empty_rows.csv') - eq_(len(ds.fields()), 10) - eq_(len(ds.field_types()), 10) - eq_(ds.fields(), ['x', 'y', 'text', 'date', 'integer', - 'boolean', 'float', 'time', 'datetime', 'empty_column']) - eq_(ds.field_types(), ['int', 'int', 'str', 'str', - 'int', 'bool', 'float', 'str', 'str', 'str']) + assert len(ds.fields()) == 10 + assert len(ds.field_types()) == 10 + assert ds.fields() == ['x', 'y', 'text', 'date', 'integer', + 'boolean', 'float', 'time', 'datetime', 'empty_column'] + assert ds.field_types() == ['int', 'int', 'str', 'str', + 'int', 'bool', 'float', 'str', 'str', 'str'] fs = ds.featureset() attr = { 'x': 0, @@ -162,146 +137,138 @@ def test_empty_rows(**kwargs): for feat in fs: if first: first = False - eq_(feat.attributes, attr) - eq_(len(feat), 10) - eq_(feat['empty_column'], u'') + assert feat.attributes == attr + assert len(feat) == 10 + assert feat['empty_column'] == u'' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_slashes(**kwargs): ds = get_csv_ds('has_attributes_with_slashes.csv') - eq_(len(ds.fields()), 3) + assert len(ds.fields()) == 3 fs = list(ds.all_features()) - eq_(fs[0].attributes, {'x': 0, 'y': 0, 'name': u'a/a'}) - eq_(fs[1].attributes, {'x': 1, 'y': 4, 'name': u'b/b'}) - eq_(fs[2].attributes, {'x': 10, 'y': 2.5, 'name': u'c/c'}) + assert fs[0].attributes == {'x': 0, 'y': 0, 'name': u'a/a'} + assert fs[1].attributes == {'x': 1, 'y': 4, 'name': u'b/b'} + assert fs[2].attributes == {'x': 10, 'y': 2.5, 'name': u'c/c'} desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_wkt_field(**kwargs): ds = get_csv_ds('wkt.csv') - eq_(len(ds.fields()), 1) - eq_(ds.fields(), ['type']) - eq_(ds.field_types(), ['str']) + assert len(ds.fields()) == 1 + assert ds.fields() == ['type'] + assert ds.field_types() == ['str'] fs = list(ds.all_features()) - # eq_(len(fs[0].geometries()),1) - eq_(fs[0].geometry.type(), mapnik.GeometryType.Point) - # eq_(len(fs[1].geometries()),1) - eq_(fs[1].geometry.type(), mapnik.GeometryType.LineString) - # eq_(len(fs[2].geometries()),1) - eq_(fs[2].geometry.type(), mapnik.GeometryType.Polygon) - # eq_(len(fs[3].geometries()),1) # one geometry, two parts - eq_(fs[3].geometry.type(), mapnik.GeometryType.Polygon) - # eq_(len(fs[4].geometries()),4) - eq_(fs[4].geometry.type(), mapnik.GeometryType.MultiPoint) - # eq_(len(fs[5].geometries()),2) - eq_(fs[5].geometry.type(), mapnik.GeometryType.MultiLineString) - # eq_(len(fs[6].geometries()),2) - eq_(fs[6].geometry.type(), mapnik.GeometryType.MultiPolygon) - # eq_(len(fs[7].geometries()),2) - eq_(fs[7].geometry.type(), mapnik.GeometryType.MultiPolygon) + assert fs[0].geometry.type() == mapnik.GeometryType.Point + assert fs[1].geometry.type() == mapnik.GeometryType.LineString + assert fs[2].geometry.type() == mapnik.GeometryType.Polygon + assert fs[3].geometry.type() == mapnik.GeometryType.Polygon + assert fs[4].geometry.type() == mapnik.GeometryType.MultiPoint + assert fs[5].geometry.type() == mapnik.GeometryType.MultiLineString + assert fs[6].geometry.type() == mapnik.GeometryType.MultiPolygon + assert fs[7].geometry.type() == mapnik.GeometryType.MultiPolygon desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Collection) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Collection + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_handling_of_missing_header(**kwargs): ds = get_csv_ds('missing_header.csv') - eq_(len(ds.fields()), 6) - eq_(ds.fields(), ['one', 'two', 'x', 'y', '_4', 'aftermissing']) + assert len(ds.fields()) == 6 + assert ds.fields() == ['one', 'two', 'x', 'y', '_4', 'aftermissing'] fs = ds.featureset() feat = fs.next() - eq_(feat['_4'], 'missing') + assert feat['_4'] == 'missing' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_handling_of_headers_that_are_numbers(**kwargs): ds = get_csv_ds('numbers_for_headers.csv') - eq_(len(ds.fields()), 5) - eq_(ds.fields(), ['x', 'y', '1990', '1991', '1992']) + assert len(ds.fields()) == 5 + assert ds.fields() == ['x', 'y', '1990', '1991', '1992'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['1990'], 1) - eq_(feat['1991'], 2) - eq_(feat['1992'], 3) - eq_(mapnik.Expression("[1991]=2").evaluate(feat), True) + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['1990'] == 1 + assert feat['1991'] == 2 + assert feat['1992'] == 3 + assert mapnik.Expression("[1991]=2").evaluate(feat) def test_quoted_numbers(**kwargs): ds = get_csv_ds('points.csv') - eq_(len(ds.fields()), 6) - eq_(ds.fields(), ['lat', 'long', 'name', 'nr', 'color', 'placements']) + assert len(ds.fields()) == 6 + assert ds.fields(), ['lat', 'long', 'name', 'nr', 'color' == 'placements'] fs = list(ds.all_features()) - eq_(fs[0]['placements'], "N,S,E,W,SW,10,5") - eq_(fs[1]['placements'], "N,S,E,W,SW,10,5") - eq_(fs[2]['placements'], "N,S,E,W,SW,10,5") - eq_(fs[3]['placements'], "N,S,E,W,SW,10,5") - eq_(fs[4]['placements'], "N,S,E,W,SW,10,5") + assert fs[0]['placements'] == "N,S,E,W,SW,10,5" + assert fs[1]['placements'] == "N,S,E,W,SW,10,5" + assert fs[2]['placements'] == "N,S,E,W,SW,10,5" + assert fs[3]['placements'] == "N,S,E,W,SW,10,5" + assert fs[4]['placements'] == "N,S,E,W,SW,10,5" desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_reading_windows_newlines(**kwargs): ds = get_csv_ds('windows_newlines.csv') - eq_(len(ds.fields()), 3) + assert len(ds.fields()) == 3 feats = list(ds.all_features()) - eq_(len(feats), 1) + assert len(feats) == 1 fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 1) - eq_(feat['y'], 10) - eq_(feat['z'], 9999.9999) + assert feat['x'] == 1 + assert feat['y'] == 10 + assert feat['z'] == 9999.9999 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_reading_mac_newlines(**kwargs): ds = get_csv_ds('mac_newlines.csv') - eq_(len(ds.fields()), 3) + assert len(ds.fields()) == 3 feats = list(ds.all_features()) - eq_(len(feats), 1) + assert len(feats) == 1 fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 1) - eq_(feat['y'], 10) - eq_(feat['z'], 9999.9999) + assert feat['x'] == 1 + assert feat['y'] == 10 + assert feat['z'] == 9999.9999 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def check_newlines(filename): ds = get_csv_ds(filename) - eq_(len(ds.fields()), 3) + assert len(ds.fields()) == 3 feats = list(ds.all_features()) - eq_(len(feats), 1) + assert len(feats) == 1 fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['line'], 'many\n lines\n of text\n with unix newlines') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['line'] == 'many\n lines\n of text\n with unix newlines' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_mixed_mac_unix_newlines(**kwargs): check_newlines('mac_newlines_with_unix_inline.csv') @@ -325,111 +292,112 @@ def test_mixed_windows_unix_newlines_escaped(**kwargs): def test_tabs(**kwargs): ds = get_csv_ds('tabs_in_csv.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'z']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'z'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], -122) - eq_(feat['y'], 48) - eq_(feat['z'], 0) + assert feat['x'] == -122 + assert feat['y'] == 48 + assert feat['z'] == 0 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_separator_pipes(**kwargs): ds = get_csv_ds('pipe_delimiters.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'z']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'z'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['z'], 'hello') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['z'] == 'hello' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_separator_semicolon(**kwargs): ds = get_csv_ds('semicolon_delimiters.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'z']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'z'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['z'], 'hello') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['z'] == 'hello' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_that_null_and_bool_keywords_are_empty_strings(**kwargs): ds = get_csv_ds('nulls_and_booleans_as_strings.csv') - eq_(len(ds.fields()), 4) - eq_(ds.fields(), ['x', 'y', 'null', 'boolean']) - eq_(ds.field_types(), ['int', 'int', 'str', 'bool']) + assert len(ds.fields()) == 4 + assert ds.fields(), ['x', 'y', 'null' == 'boolean'] + assert ds.field_types(), ['int', 'int', 'str' == 'bool'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['null'], 'null') - eq_(feat['boolean'], True) + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['null'] == 'null' + assert feat['boolean'] == True feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['null'], '') - eq_(feat['boolean'], False) + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['null'] == '' + assert feat['boolean'] == False desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point - @raises(RuntimeError) def test_that_nonexistant_query_field_throws(**kwargs): - ds = get_csv_ds('lon_lat.csv') - eq_(len(ds.fields()), 2) - eq_(ds.fields(), ['lon', 'lat']) - eq_(ds.field_types(), ['int', 'int']) - query = mapnik.Query(ds.envelope()) - for fld in ds.fields(): - query.add_property_name(fld) - # also add an invalid one, triggering throw - query.add_property_name('bogus') - ds.features(query) + with pytest.raises(RuntimeError): + ds = get_csv_ds('lon_lat.csv') + assert len(ds.fields()) == 2 + assert ds.fields(), ['lon' == 'lat'] + assert ds.field_types(), ['int' == 'int'] + query = mapnik.Query(ds.envelope()) + for fld in ds.fields(): + query.add_property_name(fld) + # also add an invalid one, triggering throw + query.add_property_name('bogus') + ds.features(query) + def test_that_leading_zeros_mean_strings(**kwargs): ds = get_csv_ds('leading_zeros.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'fips']) - eq_(ds.field_types(), ['int', 'int', 'str']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'fips'] + assert ds.field_types(), ['int', 'int' == 'str'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['fips'], '001') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['fips'] == '001' feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['fips'], '003') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['fips'] == '003' feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['fips'], '005') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['fips'] == '005' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point def test_advanced_geometry_detection(**kwargs): ds = get_csv_ds('point_wkt.csv') - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Point) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.Point ds = get_csv_ds('poly_wkt.csv') - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Polygon) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.Polygon ds = get_csv_ds('multi_poly_wkt.csv') - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Polygon) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.Polygon ds = get_csv_ds('line_wkt.csv') - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.LineString) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.LineString def test_creation_of_csv_from_in_memory_string(**kwargs): csv_string = ''' @@ -437,10 +405,10 @@ def test_creation_of_csv_from_in_memory_string(**kwargs): "POINT (120.15 48.47)","Winthrop, WA" ''' # csv plugin will test lines <= 10 chars for being fully blank ds = mapnik.Datasource(**{"type": "csv", "inline": csv_string}) - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Point) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.Point fs = ds.featureset() feat = fs.next() - eq_(feat['Name'], u"Winthrop, WA") + assert feat['Name'], u"Winthrop == WA" def test_creation_of_csv_from_in_memory_string_with_uft8(**kwargs): csv_string = ''' @@ -448,37 +416,29 @@ def test_creation_of_csv_from_in_memory_string_with_uft8(**kwargs): "POINT (120.15 48.47)","Québec" ''' # csv plugin will test lines <= 10 chars for being fully blank ds = mapnik.Datasource(**{"type": "csv", "inline": csv_string}) - eq_(ds.describe()['geometry_type'], mapnik.DataGeometryType.Point) + assert ds.describe()['geometry_type'] == mapnik.DataGeometryType.Point fs = ds.featureset() feat = fs.next() - eq_(feat['Name'], u"Québec") + assert feat['Name'] == u"Québec" def validate_geojson_datasource(ds): - eq_(len(ds.fields()), 1) - eq_(ds.fields(), ['type']) - eq_(ds.field_types(), ['str']) + assert len(ds.fields()) == 1 + assert ds.fields() == ['type'] + assert ds.field_types() == ['str'] fs = list(ds.all_features()) - # eq_(len(fs[0].geometries()),1) - eq_(fs[0].geometry.type(), mapnik.GeometryType.Point) - # eq_(len(fs[1].geometries()),1) - eq_(fs[1].geometry.type(), mapnik.GeometryType.LineString) - # eq_(len(fs[2].geometries()),1) - eq_(fs[2].geometry.type(), mapnik.GeometryType.Polygon) - # eq_(len(fs[3].geometries()),1) # one geometry, two parts - eq_(fs[3].geometry.type(), mapnik.GeometryType.Polygon) - # eq_(len(fs[4].geometries()),4) - eq_(fs[4].geometry.type(), mapnik.GeometryType.MultiPoint) - # eq_(len(fs[5].geometries()),2) - eq_(fs[5].geometry.type(), mapnik.GeometryType.MultiLineString) - # eq_(len(fs[6].geometries()),2) - eq_(fs[6].geometry.type(), mapnik.GeometryType.MultiPolygon) - # eq_(len(fs[7].geometries()),2) - eq_(fs[7].geometry.type(), mapnik.GeometryType.MultiPolygon) + assert fs[0].geometry.type() == mapnik.GeometryType.Point + assert fs[1].geometry.type() == mapnik.GeometryType.LineString + assert fs[2].geometry.type() == mapnik.GeometryType.Polygon + assert fs[3].geometry.type() == mapnik.GeometryType.Polygon + assert fs[4].geometry.type() == mapnik.GeometryType.MultiPoint + assert fs[5].geometry.type() == mapnik.GeometryType.MultiLineString + assert fs[6].geometry.type() == mapnik.GeometryType.MultiPolygon + assert fs[7].geometry.type() == mapnik.GeometryType.MultiPolygon desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Collection) - eq_(desc['name'], 'csv') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Collection + assert desc['name'] == 'csv' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_json_field1(**kwargs): ds = get_csv_ds('geojson_double_quote_escape.csv') @@ -494,129 +454,129 @@ def test_json_field3(**kwargs): def test_that_blank_undelimited_rows_are_still_parsed(**kwargs): ds = get_csv_ds('more_headers_than_column_values.csv') - eq_(len(ds.fields()), 0) - eq_(ds.fields(), []) - eq_(ds.field_types(), []) + assert len(ds.fields()) == 0 + assert ds.fields() == [] + assert ds.field_types() == [] fs = list(ds.featureset()) - eq_(len(fs), 0) + assert len(fs) == 0 desc = ds.describe() - eq_(desc['geometry_type'], None) + assert desc['geometry_type'] == None - @raises(RuntimeError) def test_that_fewer_headers_than_rows_throws(**kwargs): - # this has invalid header # so throw - get_csv_ds('more_column_values_than_headers.csv') + with pytest.raises(RuntimeError): + # this has invalid header # so throw + get_csv_ds('more_column_values_than_headers.csv') def test_that_feature_id_only_incremented_for_valid_rows(**kwargs): ds = mapnik.Datasource(type='csv', - file=os.path.join('../data/csv/warns', 'feature_id_counting.csv')) - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'id']) - eq_(ds.field_types(), ['int', 'int', 'int']) + file=os.path.join('./test/data/csv/warns', 'feature_id_counting.csv')) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'id'] + assert ds.field_types(), ['int', 'int' == 'int'] fs = ds.featureset() # first feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['id'], 1) + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['id'] == 1 # second, should have skipped bogus one feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['id'], 2) + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['id'] == 2 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 2) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 2 def test_dynamically_defining_headers1(**kwargs): ds = mapnik.Datasource(type='csv', file=os.path.join( - '../data/csv/fails', 'needs_headers_two_lines.csv'), + './test/data/csv/fails', 'needs_headers_two_lines.csv'), headers='x,y,name') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'name']) - eq_(ds.field_types(), ['int', 'int', 'str']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'name'] + assert ds.field_types(), ['int', 'int' == 'str'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['name'], 'data_name') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['name'] == 'data_name' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 2) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 2 def test_dynamically_defining_headers2(**kwargs): ds = mapnik.Datasource(type='csv', file=os.path.join( - '../data/csv/fails', 'needs_headers_one_line.csv'), + './test/data/csv/fails', 'needs_headers_one_line.csv'), headers='x,y,name') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'name']) - eq_(ds.field_types(), ['int', 'int', 'str']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'name'] + assert ds.field_types(), ['int', 'int' == 'str'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['name'], 'data_name') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['name'] == 'data_name' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 1) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 1 def test_dynamically_defining_headers3(**kwargs): ds = mapnik.Datasource(type='csv', file=os.path.join( - '../data/csv/fails', 'needs_headers_one_line_no_newline.csv'), + './test/data/csv/fails', 'needs_headers_one_line_no_newline.csv'), headers='x,y,name') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'name']) - eq_(ds.field_types(), ['int', 'int', 'str']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'name'] + assert ds.field_types(), ['int', 'int' == 'str'] fs = ds.featureset() feat = fs.next() - eq_(feat['x'], 0) - eq_(feat['y'], 0) - eq_(feat['name'], 'data_name') + assert feat['x'] == 0 + assert feat['y'] == 0 + assert feat['name'] == 'data_name' desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 1) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 1 def test_that_64bit_int_fields_work(**kwargs): ds = get_csv_ds('64bit_int.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'bigint']) - eq_(ds.field_types(), ['int', 'int', 'int']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'bigint'] + assert ds.field_types(), ['int', 'int' == 'int'] fs = ds.featureset() feat = fs.next() - eq_(feat['bigint'], 2147483648) + assert feat['bigint'] == 2147483648 feat = fs.next() - eq_(feat['bigint'], 9223372036854775807) - eq_(feat['bigint'], 0x7FFFFFFFFFFFFFFF) + assert feat['bigint'] == 9223372036854775807 + assert feat['bigint'] == 0x7FFFFFFFFFFFFFFF desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 2) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 2 def test_various_number_types(**kwargs): ds = get_csv_ds('number_types.csv') - eq_(len(ds.fields()), 3) - eq_(ds.fields(), ['x', 'y', 'floats']) - eq_(ds.field_types(), ['int', 'int', 'float']) + assert len(ds.fields()) == 3 + assert ds.fields(), ['x', 'y' == 'floats'] + assert ds.field_types(), ['int', 'int' == 'float'] fs = ds.featureset() feat = fs.next() - eq_(feat['floats'], .0) + assert feat['floats'] == .0 feat = fs.next() - eq_(feat['floats'], +.0) + assert feat['floats'] == +.0 feat = fs.next() - eq_(feat['floats'], 1e-06) + assert feat['floats'] == 1e-06 feat = fs.next() - eq_(feat['floats'], -1e-06) + assert feat['floats'] == -1e-06 feat = fs.next() - eq_(feat['floats'], 0.000001) + assert feat['floats'] == 0.000001 feat = fs.next() - eq_(feat['floats'], 1.234e+16) + assert feat['floats'] == 1.234e+16 feat = fs.next() - eq_(feat['floats'], 1.234e+16) + assert feat['floats'] == 1.234e+16 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(len(list(ds.all_features())), 8) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert len(list(ds.all_features())) == 8 def test_manually_supplied_extent(**kwargs): csv_string = ''' @@ -625,21 +585,17 @@ def test_manually_supplied_extent(**kwargs): ds = mapnik.Datasource( **{"type": "csv", "extent": "-180,-90,180,90", "inline": csv_string}) b = ds.envelope() - eq_(b.minx, -180) - eq_(b.miny, -90) - eq_(b.maxx, 180) - eq_(b.maxy, 90) + assert b.minx == -180 + assert b.miny == -90 + assert b.maxx == 180 + assert b.maxy == 90 def test_inline_geojson(**kwargs): csv_string = "geojson\n'{\"coordinates\":[-92.22568,38.59553],\"type\":\"Point\"}'" ds = mapnik.Datasource(**{"type": "csv", "inline": csv_string}) - eq_(len(ds.fields()), 0) - eq_(ds.fields(), []) - # FIXME - re-enable after https://github.com/mapnik/mapnik/issues/2319 is fixed - #fs = ds.featureset() - #feat = fs.next() - # eq_(feat.num_geometries(),1) - -if __name__ == "__main__": - setup() - [eval(run)(visual=True) for run in dir() if 'test_' in run] + assert len(ds.fields()) == 0 + assert ds.fields() == [] + fs = ds.featureset() + feat = fs.next() + assert feat.geometry.type() == mapnik.GeometryType.Point + assert feat.geometry.to_wkt() == "POINT(-92.22568 38.59553)" diff --git a/test/python_tests/datasource_test.py b/test/python_tests/datasource_test.py index 8a2183abb..5fa6780c6 100644 --- a/test/python_tests/datasource_test.py +++ b/test/python_tests/datasource_test.py @@ -1,160 +1,141 @@ -#!/usr/bin/env python import os import sys -from itertools import groupby - -from nose.tools import eq_, raises - import mapnik +import pytest -from .utilities import execution_path, run_all - -PYTHON3 = sys.version_info[0] == 3 -if PYTHON3: - xrange = range - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - +from itertools import groupby def test_that_datasources_exist(): if len(mapnik.DatasourceCache.plugin_names()) == 0: print('***NOTICE*** - no datasource plugins have been loaded') # adapted from raster_symboliser_test#test_dataraster_query_point - - -@raises(RuntimeError) def test_vrt_referring_to_missing_files(): - srs = 'epsg:32630' - if 'gdal' in mapnik.DatasourceCache.plugin_names(): - lyr = mapnik.Layer('dataraster') - lyr.datasource = mapnik.Gdal( - file='../data/raster/missing_raster.vrt', - band=1, - ) - lyr.srs = srs - _map = mapnik.Map(256, 256, srs) - _map.layers.append(lyr) - - # center of extent of raster - x, y = 556113.0, 4381428.0 # center of extent of raster - - _map.zoom_all() - - # Fancy stuff to supress output of error - # open 2 fds - null_fds = [os.open(os.devnull, os.O_RDWR) for x in xrange(2)] - # save the current file descriptors to a tuple - save = os.dup(1), os.dup(2) - # put /dev/null fds on 1 and 2 - os.dup2(null_fds[0], 1) - os.dup2(null_fds[1], 2) - - # *** run the function *** - try: - # Should RuntimeError here - list(_map.query_point(0, x, y)) - finally: - # restore file descriptors so I can print the results - os.dup2(save[0], 1) - os.dup2(save[1], 2) - # close the temporary fds - os.close(null_fds[0]) - os.close(null_fds[1]) + with pytest.raises(RuntimeError): + srs = 'epsg:32630' + if 'gdal' in mapnik.DatasourceCache.plugin_names(): + lyr = mapnik.Layer('dataraster') + lyr.datasource = mapnik.Gdal( + file='./test/data/raster/missing_raster.vrt', + band=1, + ) + lyr.srs = srs + _map = mapnik.Map(256, 256, srs) + _map.layers.append(lyr) + + # center of extent of raster + x, y = 556113.0, 4381428.0 # center of extent of raster + _map.zoom_all() + + # Fancy stuff to supress output of error + # open 2 fds + null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)] + # save the current file descriptors to a tuple + save = os.dup(1), os.dup(2) + # put /dev/null fds on 1 and 2 + os.dup2(null_fds[0], 1) + os.dup2(null_fds[1], 2) + + # *** run the function *** + try: + # Should RuntimeError here + list(_map.query_point(0, x, y)) + finally: + # restore file descriptors so I can print the results + os.dup2(save[0], 1) + os.dup2(save[1], 2) + # close the temporary fds + os.close(null_fds[0]) + os.close(null_fds[1]) def test_field_listing(): if 'shape' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Shapefile(file='../data/shp/poly.shp') + ds = mapnik.Shapefile(file='./test/data/shp/poly.shp') fields = ds.fields() - eq_(fields, ['AREA', 'EAS_ID', 'PRFEDEA']) + assert fields, ['AREA', 'EAS_ID' == 'PRFEDEA'] desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Polygon) - eq_(desc['name'], 'shape') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Polygon + assert desc['name'] == 'shape' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' def test_total_feature_count_shp(): if 'shape' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Shapefile(file='../data/shp/poly.shp') + ds = mapnik.Shapefile(file='./test/data/shp/poly.shp') features = ds.all_features() num_feats = len(list(features)) - eq_(num_feats, 10) - + assert num_feats == 10 def test_total_feature_count_json(): if 'ogr' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Ogr(file='../data/json/points.geojson', layer_by_index=0) + ds = mapnik.Ogr(file='./test/data/json/points.geojson', layer_by_index=0) desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(desc['name'], 'ogr') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert desc['name'] == 'ogr' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' features = ds.all_features() num_feats = len(list(features)) - eq_(num_feats, 5) + assert num_feats == 5 def test_sqlite_reading(): if 'sqlite' in mapnik.DatasourceCache.plugin_names(): ds = mapnik.SQLite( - file='../data/sqlite/world.sqlite', + file='./test/data/sqlite/world.sqlite', table_by_index=0) desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Polygon) - eq_(desc['name'], 'sqlite') - eq_(desc['type'], mapnik.DataType.Vector) - eq_(desc['encoding'], 'utf-8') + assert desc['geometry_type'] == mapnik.DataGeometryType.Polygon + assert desc['name'] == 'sqlite' + assert desc['type'] == mapnik.DataType.Vector + assert desc['encoding'] == 'utf-8' features = ds.all_features() num_feats = len(list(features)) - eq_(num_feats, 245) + assert num_feats == 245 def test_reading_json_from_string(): - with open('../data/json/points.geojson', 'r') as f: + with open('./test/data/json/points.geojson', 'r') as f: json = f.read() if 'ogr' in mapnik.DatasourceCache.plugin_names(): ds = mapnik.Ogr(file=json, layer_by_index=0) features = ds.all_features() num_feats = len(list(features)) - eq_(num_feats, 5) + assert num_feats == 5 def test_feature_envelope(): if 'shape' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Shapefile(file='../data/shp/poly.shp') + ds = mapnik.Shapefile(file='./test/data/shp/poly.shp') features = ds.all_features() for feat in features: env = feat.envelope() contains = ds.envelope().contains(env) - eq_(contains, True) + assert contains == True intersects = ds.envelope().contains(env) - eq_(intersects, True) + assert intersects == True def test_feature_attributes(): if 'shape' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Shapefile(file='../data/shp/poly.shp') + ds = mapnik.Shapefile(file='./test/data/shp/poly.shp') features = list(ds.all_features()) feat = features[0] attrs = {'PRFEDEA': u'35043411', 'EAS_ID': 168, 'AREA': 215229.266} - eq_(feat.attributes, attrs) - eq_(ds.fields(), ['AREA', 'EAS_ID', 'PRFEDEA']) - eq_(ds.field_types(), ['float', 'int', 'str']) + assert feat.attributes == attrs + assert ds.fields(), ['AREA', 'EAS_ID' == 'PRFEDEA'] + assert ds.field_types(), ['float', 'int' == 'str'] def test_ogr_layer_by_sql(): if 'ogr' in mapnik.DatasourceCache.plugin_names(): - ds = mapnik.Ogr(file='../data/shp/poly.shp', + ds = mapnik.Ogr(file='./test/data/shp/poly.shp', layer_by_sql='SELECT * FROM poly WHERE EAS_ID = 168') features = ds.all_features() num_feats = len(list(features)) - eq_(num_feats, 1) + assert num_feats == 1 def test_hit_grid(): @@ -166,12 +147,12 @@ def rle_encode(l): m = mapnik.Map(256, 256) try: - mapnik.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml') + mapnik.load_map(m, './test/data/good_maps/agg_poly_gamma_map.xml') m.zoom_all() join_field = 'NAME' fg = [] # feature grid - for y in xrange(0, 256, 4): - for x in xrange(0, 256, 4): + for y in range(0, 256, 4): + for x in range(0, 256, 4): featureset = m.query_map_point(0, x, y) added = False for feature in featureset: @@ -180,14 +161,9 @@ def rle_encode(l): if not added: fg.append('') hit_list = '|'.join(rle_encode(fg)) - eq_(hit_list[:16], '730:|2:Greenland') - eq_(hit_list[-12:], '1:Chile|812:') + assert hit_list[:16] == '730:|2:Greenland' + assert hit_list[-12:] == '1:Chile|812:' except RuntimeError as e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(str(e)) - - -if __name__ == '__main__': - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) diff --git a/test/python_tests/datasource_xml_template_test.py b/test/python_tests/datasource_xml_template_test.py index b561d93e6..1a0c06131 100644 --- a/test/python_tests/datasource_xml_template_test.py +++ b/test/python_tests/datasource_xml_template_test.py @@ -1,27 +1,18 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_datasource_template_is_working(): m = mapnik.Map(256, 256) - try: - mapnik.load_map(m, '../data/good_maps/datasource.xml') - except RuntimeError as e: - if "Required parameter 'type'" in str(e): - raise RuntimeError(e) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + mapnik.load_map(m, './test/data/good_maps/datasource.xml') + for layer in m.layers: + layer_bbox = layer.envelope() + bbox = None + first = True + for feature in layer.datasource: + assert feature.envelope() == feature.geometry.envelope() + assert layer_bbox.contains(feature.envelope()) + if first: + first = False + bbox = feature.envelope() + else: + bbox += feature.envelope() + assert layer_bbox == bbox diff --git a/test/python_tests/extra_map_props_test.py b/test/python_tests/extra_map_props_test.py index ac9e7482d..1b8796763 100644 --- a/test/python_tests/extra_map_props_test.py +++ b/test/python_tests/extra_map_props_test.py @@ -1,48 +1,32 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_arbitrary_parameters_attached_to_map(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/extra_arbitary_map_parameters.xml') - eq_(len(m.parameters), 5) - eq_(m.parameters['key'], 'value2') - eq_(m.parameters['key3'], 'value3') - eq_(m.parameters['unicode'], u'iván') - eq_(m.parameters['integer'], 10) - eq_(m.parameters['decimal'], .999) + mapnik.load_map(m, './test/data/good_maps/extra_arbitary_map_parameters.xml') + assert len(m.parameters) == 5 + assert m.parameters['key'] == 'value2' + assert m.parameters['key3'] == 'value3' + assert m.parameters['unicode'] == u'iván' + assert m.parameters['integer'] == 10 + assert m.parameters['decimal'] == .999 m2 = mapnik.Map(256, 256) for k, v in m.parameters: m2.parameters.append(mapnik.Parameter(k, v)) - eq_(len(m2.parameters), 5) - eq_(m2.parameters['key'], 'value2') - eq_(m2.parameters['key3'], 'value3') - eq_(m2.parameters['unicode'], u'iván') - eq_(m2.parameters['integer'], 10) - eq_(m2.parameters['decimal'], .999) + assert len(m2.parameters) == 5 + assert m2.parameters['key'] == 'value2' + assert m2.parameters['key3'] == 'value3' + assert m2.parameters['unicode'] == u'iván' + assert m2.parameters['integer'] == 10 + assert m2.parameters['decimal'] == .999 map_string = mapnik.save_map_to_string(m) m3 = mapnik.Map(256, 256) mapnik.load_map_from_string(m3, map_string) - eq_(len(m3.parameters), 5) - eq_(m3.parameters['key'], 'value2') - eq_(m3.parameters['key3'], 'value3') - eq_(m3.parameters['unicode'], u'iván') - eq_(m3.parameters['integer'], 10) - eq_(m3.parameters['decimal'], .999) + assert len(m3.parameters) == 5 + assert m3.parameters['key'] == 'value2' + assert m3.parameters['key3'] == 'value3' + assert m3.parameters['unicode'] == u'iván' + assert m3.parameters['integer'] == 10 + assert m3.parameters['decimal'] == .999 def test_serializing_arbitrary_parameters(): @@ -52,9 +36,5 @@ def test_serializing_arbitrary_parameters(): m2 = mapnik.Map(1, 1) mapnik.load_map_from_string(m2, mapnik.save_map_to_string(m)) - eq_(m2.parameters['width'], m.width) - eq_(m2.parameters['height'], m.height) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert m2.parameters['width'] == m.width + assert m2.parameters['height'] == m.height diff --git a/test/python_tests/feature_test.py b/test/python_tests/feature_test.py index 7a544af1a..d4f8afc61 100644 --- a/test/python_tests/feature_test.py +++ b/test/python_tests/feature_test.py @@ -1,26 +1,17 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - from binascii import unhexlify - -from nose.tools import eq_, raises - import mapnik - -from .utilities import run_all - +import pytest def test_default_constructor(): f = mapnik.Feature(mapnik.Context(), 1) - eq_(f is not None, True) + assert f is not None def test_feature_geo_interface(): ctx = mapnik.Context() feat = mapnik.Feature(ctx, 1) feat.geometry = mapnik.Geometry.from_wkt('Point (0 0)') - eq_(feat.__geo_interface__['geometry'], { - u'type': u'Point', u'coordinates': [0, 0]}) + assert feat.__geo_interface__['geometry'] == {u'type': u'Point', u'coordinates': [0, 0]} def test_python_extended_constructor(): @@ -31,15 +22,15 @@ def test_python_extended_constructor(): wkt = 'POLYGON ((35 10, 10 20, 15 40, 45 45, 35 10),(20 30, 35 35, 30 20, 20 30))' f.geometry = mapnik.Geometry.from_wkt(wkt) f['foo'] = 'bar' - eq_(f['foo'], 'bar') - eq_(f.envelope(), mapnik.Box2d(10.0, 10.0, 45.0, 45.0)) + assert f['foo'] == 'bar' + assert f.envelope(), mapnik.Box2d(10.0, 10.0, 45.0 == 45.0) # reset f['foo'] = u"avión" - eq_(f['foo'], u"avión") + assert f['foo'] == u"avión" f['foo'] = 1.4 - eq_(f['foo'], 1.4) + assert f['foo'] == 1.4 f['foo'] = True - eq_(f['foo'], True) + assert f['foo'] == True def test_add_geom_wkb(): @@ -49,13 +40,13 @@ def test_add_geom_wkb(): if hasattr(geometry, 'is_valid'): # Those are only available when python-mapnik has been built with # boost >= 1.56. - eq_(geometry.is_valid(), True) - eq_(geometry.is_simple(), True) - eq_(geometry.envelope(), mapnik.Box2d(10.0, 10.0, 40.0, 40.0)) + assert geometry.is_valid() == True + assert geometry.is_simple() == True + assert geometry.envelope(), mapnik.Box2d(10.0, 10.0, 40.0 == 40.0) geometry.correct() if hasattr(geometry, 'is_valid'): # valid after calling correct - eq_(geometry.is_valid(), True) + assert geometry.is_valid() == True def test_feature_expression_evaluation(): @@ -63,13 +54,13 @@ def test_feature_expression_evaluation(): context.push('name') f = mapnik.Feature(context, 1) f['name'] = 'a' - eq_(f['name'], u'a') + assert f['name'] == u'a' expr = mapnik.Expression("[name]='a'") evaluated = expr.evaluate(f) - eq_(evaluated, True) + assert evaluated == True num_attributes = len(f) - eq_(num_attributes, 1) - eq_(f.id(), 1) + assert num_attributes == 1 + assert f.id() == 1 # https://github.com/mapnik/mapnik/issues/933 @@ -79,16 +70,16 @@ def test_feature_expression_evaluation_missing_attr(): context.push('name') f = mapnik.Feature(context, 1) f['name'] = u'a' - eq_(f['name'], u'a') + assert f['name'] == u'a' expr = mapnik.Expression("[fielddoesnotexist]='a'") - eq_('fielddoesnotexist' in f, False) + assert not 'fielddoesnotexist' in f try: expr.evaluate(f) except Exception as e: - eq_("Key does not exist" in str(e), True) + assert "Key does not exist" in str(e) == True num_attributes = len(f) - eq_(num_attributes, 1) - eq_(f.id(), 1) + assert num_attributes == 1 + assert f.id() == 1 # https://github.com/mapnik/mapnik/issues/934 @@ -98,31 +89,27 @@ def test_feature_expression_evaluation_attr_with_spaces(): context.push('name with space') f = mapnik.Feature(context, 1) f['name with space'] = u'a' - eq_(f['name with space'], u'a') + assert f['name with space'] == u'a' expr = mapnik.Expression("[name with space]='a'") - eq_(str(expr), "([name with space]='a')") - eq_(expr.evaluate(f), True) + assert str(expr) == "([name with space]='a')" + assert expr.evaluate(f) == True # https://github.com/mapnik/mapnik/issues/2390 - -@raises(RuntimeError) def test_feature_from_geojson(): - ctx = mapnik.Context() - inline_string = """ - { - "geometry" : { - "coordinates" : [ 0,0 ] - "type" : "Point" - }, - "type" : "Feature", - "properties" : { - "this":"that" - "known":"nope because missing comma" - } - } - """ - mapnik.Feature.from_geojson(inline_string, ctx) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + with pytest.raises(RuntimeError): + ctx = mapnik.Context() + inline_string = """ + { + "geometry" : { + "coordinates" : [ 0,0 ] + "type" : "Point" + }, + "type" : "Feature", + "properties" : { + "this":"that" + "known":"nope because missing comma" + } + } + """ + mapnik.Feature.from_geojson(inline_string, ctx) diff --git a/test/python_tests/filter_test.py b/test/python_tests/filter_test.py index 39deb5b2f..641d6950f 100644 --- a/test/python_tests/filter_test.py +++ b/test/python_tests/filter_test.py @@ -1,18 +1,5 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -import sys - -from nose.tools import eq_, raises - import mapnik - -from .utilities import run_all - -PYTHON3 = sys.version_info[0] == 3 -if PYTHON3: - long = int - unicode = str - +import pytest if hasattr(mapnik, 'Expression'): mapnik.Filter = mapnik.Expression @@ -96,11 +83,11 @@ def test_filter_init(): first = filters[0] for f in filters: - eq_(str(first), str(f)) + assert str(first) == str(f) s = m.find_style('s2') - eq_(s.filter_mode, mapnik.filter_mode.FIRST) + assert s.filter_mode == mapnik.filter_mode.FIRST def test_geometry_type_eval(): @@ -110,45 +97,42 @@ def test_geometry_type_eval(): f = mapnik.Feature(context2, 0) f["mapnik::geometry_type"] = 'sneaky' expr = mapnik.Expression("[mapnik::geometry_type]") - eq_(expr.evaluate(f), 0) + assert expr.evaluate(f) == 0 expr = mapnik.Expression("[mapnik::geometry_type]") context = mapnik.Context() # no geometry f = mapnik.Feature(context, 0) - eq_(expr.evaluate(f), 0) - eq_(mapnik.Expression("[mapnik::geometry_type]=0").evaluate(f), True) + assert expr.evaluate(f) == 0 + assert mapnik.Expression("[mapnik::geometry_type]=0").evaluate(f) # POINT = 1 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt('POINT(10 40)') - eq_(expr.evaluate(f), 1) - eq_(mapnik.Expression("[mapnik::geometry_type]=point").evaluate(f), True) + assert expr.evaluate(f) == 1 + assert mapnik.Expression("[mapnik::geometry_type]=point").evaluate(f) # LINESTRING = 2 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt('LINESTRING (30 10, 10 30, 40 40)') - eq_(expr.evaluate(f), 2) - eq_(mapnik.Expression( - "[mapnik::geometry_type] = linestring").evaluate(f), True) + assert expr.evaluate(f) == 2 + assert mapnik.Expression("[mapnik::geometry_type] = linestring").evaluate(f) # POLYGON = 3 f = mapnik.Feature(context, 0) f.geometry = mapnik.Geometry.from_wkt( 'POLYGON ((30 10, 10 20, 20 40, 40 40, 30 10))') - eq_(expr.evaluate(f), 3) - eq_(mapnik.Expression( - "[mapnik::geometry_type] = polygon").evaluate(f), True) + assert expr.evaluate(f) == 3 + assert mapnik.Expression("[mapnik::geometry_type] = polygon").evaluate(f) # COLLECTION = 4 f = mapnik.Feature(context, 0) geom = mapnik.Geometry.from_wkt( 'GEOMETRYCOLLECTION(POLYGON((1 1,2 1,2 2,1 2,1 1)),POINT(2 3),LINESTRING(2 3,3 4))') f.geometry = geom - eq_(expr.evaluate(f), 4) - eq_(mapnik.Expression( - "[mapnik::geometry_type] = collection").evaluate(f), True) + assert expr.evaluate(f) == 4 + assert mapnik.Expression("[mapnik::geometry_type] = collection").evaluate(f) def test_regex_match(): @@ -157,7 +141,7 @@ def test_regex_match(): f = mapnik.Feature(context, 0) f["name"] = 'test' expr = mapnik.Expression("[name].match('test')") - eq_(expr.evaluate(f), True) # 1 == True + assert expr.evaluate(f) # 1 == True def test_unicode_regex_match(): @@ -166,7 +150,7 @@ def test_unicode_regex_match(): f = mapnik.Feature(context, 0) f["name"] = 'Québec' expr = mapnik.Expression("[name].match('Québec')") - eq_(expr.evaluate(f), True) # 1 == True + assert expr.evaluate(f) # 1 == True def test_regex_replace(): @@ -175,12 +159,12 @@ def test_regex_replace(): f = mapnik.Feature(context, 0) f["name"] = 'test' expr = mapnik.Expression("[name].replace('(\\B)|( )','$1 ')") - eq_(expr.evaluate(f), 't e s t') + assert expr.evaluate(f) == 't e s t' def test_unicode_regex_replace_to_str(): expr = mapnik.Expression("[name].replace('(\\B)|( )','$1 ')") - eq_(str(expr), "[name].replace('(\\B)|( )','$1 ')") + assert str(expr), "[name].replace('(\\B)|( )' == '$1 ')" def test_unicode_regex_replace(): @@ -190,7 +174,7 @@ def test_unicode_regex_replace(): f["name"] = 'Québec' expr = mapnik.Expression("[name].replace('(\\B)|( )','$1 ')") # will fail if -DBOOST_REGEX_HAS_ICU is not defined - eq_(expr.evaluate(f), u'Q u é b e c') + assert expr.evaluate(f) == u'Q u é b e c' def test_float_precision(): @@ -199,16 +183,16 @@ def test_float_precision(): f = mapnik.Feature(context, 0) f["num1"] = 1.0000 f["num2"] = 1.0001 - eq_(f["num1"], 1.0000) - eq_(f["num2"], 1.0001) + assert f["num1"] == 1.0000 + assert f["num2"] == 1.0001 expr = mapnik.Expression("[num1] = 1.0000") - eq_(expr.evaluate(f), True) + assert expr.evaluate(f) expr = mapnik.Expression("[num1].match('1')") - eq_(expr.evaluate(f), True) + assert expr.evaluate(f) expr = mapnik.Expression("[num2] = 1.0001") - eq_(expr.evaluate(f), True) + assert expr.evaluate(f) expr = mapnik.Expression("[num2].match('1.0001')") - eq_(expr.evaluate(f), True) + assert expr.evaluate(f) def test_string_matching_on_precision(): @@ -216,9 +200,9 @@ def test_string_matching_on_precision(): context.push('num') f = mapnik.Feature(context, 0) f["num"] = "1.0000" - eq_(f["num"], "1.0000") + assert f["num"] == "1.0000" expr = mapnik.Expression("[num].match('.*(^0|00)$')") - eq_(expr.evaluate(f), True) + assert expr.evaluate(f) def test_creation_of_null_value(): @@ -226,12 +210,12 @@ def test_creation_of_null_value(): context.push('nv') f = mapnik.Feature(context, 0) f["nv"] = None - eq_(f["nv"], None) - eq_(f["nv"] is None, True) + assert f["nv"] == None + assert f["nv"] is None # test boolean f["nv"] = 0 - eq_(f["nv"], 0) - eq_(f["nv"] is not None, True) + assert f["nv"] == 0 + assert f["nv"] is not None def test_creation_of_bool(): @@ -239,39 +223,39 @@ def test_creation_of_bool(): context.push('bool') f = mapnik.Feature(context, 0) f["bool"] = True - eq_(f["bool"], True) + assert f["bool"] # TODO - will become int of 1 do to built in boost python conversion # https://github.com/mapnik/mapnik/issues/1873 - eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), True) + assert isinstance(f["bool"], bool) or isinstance(f["bool"], int) f["bool"] = False - eq_(f["bool"], False) - eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), True) + assert f["bool"] == False + assert isinstance(f["bool"], bool) or isinstance(f["bool"], int) # test NoneType f["bool"] = None - eq_(f["bool"], None) - eq_(isinstance(f["bool"], bool) or isinstance(f["bool"], long), False) + assert f["bool"] == None + assert not isinstance(f["bool"], bool) or isinstance(f["bool"], int) # test integer f["bool"] = 0 - eq_(f["bool"], 0) + assert f["bool"] == 0 # https://github.com/mapnik/mapnik/issues/1873 # ugh, boost_python's built into converter does not work right - # eq_(isinstance(f["bool"],bool),False) + # assert isinstance(f["bool"],bool) == False null_equality = [ - ['hello', False, unicode], - [u'', False, unicode], - [0, False, long], - [123, False, long], + ['hello', False, str], + [u'', False, str], + [0, False, int], + [123, False, int], [0.0, False, float], [123.123, False, float], [.1, False, float], # TODO - should become bool: https://github.com/mapnik/mapnik/issues/1873 - [False, False, long], + [False, False, int], # TODO - should become bool: https://github.com/mapnik/mapnik/issues/1873 - [True, False, long], + [True, False, int], [None, True, None], - [2147483648, False, long], - [922337203685477580, False, long] + [2147483648, False, int], + [922337203685477580, False, int] ] @@ -280,16 +264,15 @@ def test_expressions_with_null_equality(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = eq[0] - eq_(f["prop"], eq[0]) + assert f["prop"] == eq[0] if eq[0] is None: - eq_(f["prop"] is None, True) + assert f["prop"] is None else: - eq_(isinstance(f['prop'], eq[2]), True, - '%s is not an instance of %s' % (f['prop'], eq[2])) + assert isinstance(f['prop'], eq[2]), '%s is not an instance of %s' % (f['prop'], eq[2]) expr = mapnik.Expression("[prop] = null") - eq_(expr.evaluate(f), eq[1]) + assert expr.evaluate(f) == eq[1] expr = mapnik.Expression("[prop] is null") - eq_(expr.evaluate(f), eq[1]) + assert expr.evaluate(f) == eq[1] def test_expressions_with_null_equality2(): @@ -297,35 +280,34 @@ def test_expressions_with_null_equality2(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = eq[0] - eq_(f["prop"], eq[0]) + assert f["prop"] == eq[0] if eq[0] is None: - eq_(f["prop"] is None, True) + assert f["prop"] is None else: - eq_(isinstance(f['prop'], eq[2]), True, - '%s is not an instance of %s' % (f['prop'], eq[2])) + assert isinstance(f['prop'], eq[2]), '%s is not an instance of %s' % (f['prop'], eq[2]) # TODO - support `is not` syntax: # https://github.com/mapnik/mapnik/issues/796 expr = mapnik.Expression("not [prop] is null") - eq_(expr.evaluate(f), not eq[1]) + assert not expr.evaluate(f) == eq[1] # https://github.com/mapnik/mapnik/issues/1642 expr = mapnik.Expression("[prop] != null") - eq_(expr.evaluate(f), not eq[1]) + assert not expr.evaluate(f) == eq[1] truthyness = [ - [u'hello', True, unicode], - [u'', False, unicode], - [0, False, long], - [123, True, long], + [u'hello', True, str], + [u'', False, str], + [0, False, int], + [123, True, int], [0.0, False, float], [123.123, True, float], [.1, True, float], # TODO - should become bool: https://github.com/mapnik/mapnik/issues/1873 - [False, False, long], + [False, False, int], # TODO - should become bool: https://github.com/mapnik/mapnik/issues/1873 - [True, True, long], + [True, True, int], [None, False, None], - [2147483648, True, long], - [922337203685477580, True, long] + [2147483648, True, int], + [922337203685477580, True, int] ] @@ -334,26 +316,25 @@ def test_expressions_for_thruthyness(): for eq in truthyness: f = mapnik.Feature(context, 0) f["prop"] = eq[0] - eq_(f["prop"], eq[0]) + assert f["prop"] == eq[0] if eq[0] is None: - eq_(f["prop"] is None, True) + assert f["prop"] is None else: - eq_(isinstance(f['prop'], eq[2]), True, - '%s is not an instance of %s' % (f['prop'], eq[2])) + assert isinstance(f['prop'], eq[2]), '%s is not an instance of %s' % (f['prop'], eq[2]) expr = mapnik.Expression("[prop]") - eq_(expr.to_bool(f), eq[1]) + assert expr.to_bool(f) == eq[1] expr = mapnik.Expression("not [prop]") - eq_(expr.to_bool(f), not eq[1]) + assert not expr.to_bool(f) == eq[1] expr = mapnik.Expression("! [prop]") - eq_(expr.to_bool(f), not eq[1]) + assert not expr.to_bool(f) == eq[1] # also test if feature does not have property at all f2 = mapnik.Feature(context, 1) # no property existing will return value_null since # https://github.com/mapnik/mapnik/commit/562fada9d0f680f59b2d9f396c95320a0d753479#include/mapnik/feature.hpp - eq_(f2["prop"] is None, True) + assert f2["prop"] is None expr = mapnik.Expression("[prop]") - eq_(expr.evaluate(f2), None) - eq_(expr.to_bool(f2), False) + assert expr.evaluate(f2) == None + assert expr.to_bool(f2) == False # https://github.com/mapnik/mapnik/issues/1859 @@ -364,93 +345,86 @@ def test_if_null_and_empty_string_are_equal(): f["empty"] = u"" f["null"] = None # ensure base assumptions are good - eq_(mapnik.Expression("[empty] = ''").to_bool(f), True) - eq_(mapnik.Expression("[null] = null").to_bool(f), True) - eq_(mapnik.Expression("[empty] != ''").to_bool(f), False) - eq_(mapnik.Expression("[null] != null").to_bool(f), False) + assert mapnik.Expression("[empty] = ''").to_bool(f) + assert mapnik.Expression("[null] = null").to_bool(f) + assert not mapnik.Expression("[empty] != ''").to_bool(f) + assert not mapnik.Expression("[null] != null").to_bool(f) # now test expected behavior - eq_(mapnik.Expression("[null] = ''").to_bool(f), False) - eq_(mapnik.Expression("[empty] = null").to_bool(f), False) - eq_(mapnik.Expression("[empty] != null").to_bool(f), True) + assert not mapnik.Expression("[null] = ''").to_bool(f) + assert not mapnik.Expression("[empty] = null").to_bool(f) + assert mapnik.Expression("[empty] != null").to_bool(f) # this one is the back compatibility shim - eq_(mapnik.Expression("[null] != ''").to_bool(f), False) + assert not mapnik.Expression("[null] != ''").to_bool(f) def test_filtering_nulls_and_empty_strings(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = u"hello" - eq_(f["prop"], u"hello") - eq_(mapnik.Expression("[prop]").to_bool(f), True) - eq_(mapnik.Expression("! [prop]").to_bool(f), False) - eq_(mapnik.Expression("[prop] != null").to_bool(f), True) - eq_(mapnik.Expression("[prop] != ''").to_bool(f), True) - eq_(mapnik.Expression("[prop] != null and [prop] != ''").to_bool(f), True) - eq_(mapnik.Expression("[prop] != null or [prop] != ''").to_bool(f), True) + assert f["prop"] == u"hello" + assert mapnik.Expression("[prop]").to_bool(f) + assert not mapnik.Expression("! [prop]").to_bool(f) + assert mapnik.Expression("[prop] != null").to_bool(f) + assert mapnik.Expression("[prop] != ''").to_bool(f) + assert mapnik.Expression("[prop] != null and [prop] != ''").to_bool(f) + assert mapnik.Expression("[prop] != null or [prop] != ''").to_bool(f) f["prop2"] = u"" - eq_(f["prop2"], u"") - eq_(mapnik.Expression("[prop2]").to_bool(f), False) - eq_(mapnik.Expression("! [prop2]").to_bool(f), True) - eq_(mapnik.Expression("[prop2] != null").to_bool(f), True) - eq_(mapnik.Expression("[prop2] != ''").to_bool(f), False) - eq_(mapnik.Expression("[prop2] = ''").to_bool(f), True) - eq_(mapnik.Expression("[prop2] != null or [prop2] != ''").to_bool(f), True) - eq_(mapnik.Expression( - "[prop2] != null and [prop2] != ''").to_bool(f), False) + assert f["prop2"] == u"" + assert not mapnik.Expression("[prop2]").to_bool(f) + assert mapnik.Expression("! [prop2]").to_bool(f) + assert mapnik.Expression("[prop2] != null").to_bool(f) + assert not mapnik.Expression("[prop2] != ''").to_bool(f) + assert mapnik.Expression("[prop2] = ''").to_bool(f) + assert mapnik.Expression("[prop2] != null or [prop2] != ''").to_bool(f) + assert not mapnik.Expression("[prop2] != null and [prop2] != ''").to_bool(f) f["prop3"] = None - eq_(f["prop3"], None) - eq_(mapnik.Expression("[prop3]").to_bool(f), False) - eq_(mapnik.Expression("! [prop3]").to_bool(f), True) - eq_(mapnik.Expression("[prop3] != null").to_bool(f), False) - eq_(mapnik.Expression("[prop3] = null").to_bool(f), True) + assert f["prop3"] == None + assert not mapnik.Expression("[prop3]").to_bool(f) + assert mapnik.Expression("! [prop3]").to_bool(f) + assert not mapnik.Expression("[prop3] != null").to_bool(f) + assert mapnik.Expression("[prop3] = null").to_bool(f) # https://github.com/mapnik/mapnik/issues/1859 - #eq_(mapnik.Expression("[prop3] != ''").to_bool(f),True) - eq_(mapnik.Expression("[prop3] != ''").to_bool(f), False) + #assert mapnik.Expression("[prop3] != ''").to_bool(f) == True + assert not mapnik.Expression("[prop3] != ''").to_bool(f) - eq_(mapnik.Expression("[prop3] = ''").to_bool(f), False) + assert not mapnik.Expression("[prop3] = ''").to_bool(f) # https://github.com/mapnik/mapnik/issues/1859 - #eq_(mapnik.Expression("[prop3] != null or [prop3] != ''").to_bool(f),True) - eq_(mapnik.Expression( - "[prop3] != null or [prop3] != ''").to_bool(f), False) + #assert mapnik.Expression("[prop3] != null or [prop3] != ''").to_bool(f) == True + assert not mapnik.Expression("[prop3] != null or [prop3] != ''").to_bool(f) - eq_(mapnik.Expression( - "[prop3] != null and [prop3] != ''").to_bool(f), False) + assert not mapnik.Expression("[prop3] != null and [prop3] != ''").to_bool(f) # attr not existing should behave the same as prop3 - eq_(mapnik.Expression("[prop4]").to_bool(f), False) - eq_(mapnik.Expression("! [prop4]").to_bool(f), True) - eq_(mapnik.Expression("[prop4] != null").to_bool(f), False) - eq_(mapnik.Expression("[prop4] = null").to_bool(f), True) + assert not mapnik.Expression("[prop4]").to_bool(f) + assert mapnik.Expression("! [prop4]").to_bool(f) + assert not mapnik.Expression("[prop4] != null").to_bool(f) + assert mapnik.Expression("[prop4] = null").to_bool(f) # https://github.com/mapnik/mapnik/issues/1859 - ##eq_(mapnik.Expression("[prop4] != ''").to_bool(f),True) - eq_(mapnik.Expression("[prop4] != ''").to_bool(f), False) + ##assert mapnik.Expression("[prop4] != ''").to_bool(f) == True + assert not mapnik.Expression("[prop4] != ''").to_bool(f) - eq_(mapnik.Expression("[prop4] = ''").to_bool(f), False) + assert not mapnik.Expression("[prop4] = ''").to_bool(f) # https://github.com/mapnik/mapnik/issues/1859 - ##eq_(mapnik.Expression("[prop4] != null or [prop4] != ''").to_bool(f),True) - eq_(mapnik.Expression( - "[prop4] != null or [prop4] != ''").to_bool(f), False) + ##assert mapnik.Expression("[prop4] != null or [prop4] != ''").to_bool(f) == True + assert not mapnik.Expression("[prop4] != null or [prop4] != ''").to_bool(f) - eq_(mapnik.Expression( - "[prop4] != null and [prop4] != ''").to_bool(f), False) + assert not mapnik.Expression("[prop4] != null and [prop4] != ''").to_bool(f) f["prop5"] = False - eq_(f["prop5"], False) - eq_(mapnik.Expression("[prop5]").to_bool(f), False) - eq_(mapnik.Expression("! [prop5]").to_bool(f), True) - eq_(mapnik.Expression("[prop5] != null").to_bool(f), True) - eq_(mapnik.Expression("[prop5] = null").to_bool(f), False) - eq_(mapnik.Expression("[prop5] != ''").to_bool(f), True) - eq_(mapnik.Expression("[prop5] = ''").to_bool(f), False) - eq_(mapnik.Expression("[prop5] != null or [prop5] != ''").to_bool(f), True) - eq_(mapnik.Expression( - "[prop5] != null and [prop5] != ''").to_bool(f), True) + assert f["prop5"] == False + assert not mapnik.Expression("[prop5]").to_bool(f) + assert mapnik.Expression("! [prop5]").to_bool(f) + assert mapnik.Expression("[prop5] != null").to_bool(f) + assert not mapnik.Expression("[prop5] = null").to_bool(f) + assert mapnik.Expression("[prop5] != ''").to_bool(f) + assert not mapnik.Expression("[prop5] = ''").to_bool(f) + assert mapnik.Expression("[prop5] != null or [prop5] != ''").to_bool(f) + assert mapnik.Expression("[prop5] != null and [prop5] != ''").to_bool(f) # note, we need to do [prop5] != 0 here instead of false due to this bug: # https://github.com/mapnik/mapnik/issues/1873 - eq_(mapnik.Expression( - "[prop5] != null and [prop5] != '' and [prop5] != 0").to_bool(f), False) + assert not mapnik.Expression("[prop5] != null and [prop5] != '' and [prop5] != 0").to_bool(f) # https://github.com/mapnik/mapnik/issues/1872 @@ -459,12 +433,12 @@ def test_falseyness_comparision(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = 0 - eq_(mapnik.Expression("[prop]").to_bool(f), False) - eq_(mapnik.Expression("[prop] = false").to_bool(f), True) - eq_(mapnik.Expression("not [prop] != false").to_bool(f), True) - eq_(mapnik.Expression("not [prop] = true").to_bool(f), True) - eq_(mapnik.Expression("[prop] = true").to_bool(f), False) - eq_(mapnik.Expression("[prop] != true").to_bool(f), True) + assert not mapnik.Expression("[prop]").to_bool(f) + assert mapnik.Expression("[prop] = false").to_bool(f) + assert mapnik.Expression("not [prop] != false").to_bool(f) + assert mapnik.Expression("not [prop] = true").to_bool(f) + assert not mapnik.Expression("[prop] = true").to_bool(f) + assert mapnik.Expression("[prop] != true").to_bool(f) # https://github.com/mapnik/mapnik/issues/1806, fixed by # https://github.com/mapnik/mapnik/issues/1872 @@ -474,12 +448,12 @@ def test_truthyness_comparision(): context = mapnik.Context() f = mapnik.Feature(context, 0) f["prop"] = 1 - eq_(mapnik.Expression("[prop]").to_bool(f), True) - eq_(mapnik.Expression("[prop] = false").to_bool(f), False) - eq_(mapnik.Expression("not [prop] != false").to_bool(f), False) - eq_(mapnik.Expression("not [prop] = true").to_bool(f), False) - eq_(mapnik.Expression("[prop] = true").to_bool(f), True) - eq_(mapnik.Expression("[prop] != true").to_bool(f), False) + assert mapnik.Expression("[prop]").to_bool(f) == True + assert mapnik.Expression("[prop] = false").to_bool(f) == False + assert mapnik.Expression("not [prop] != false").to_bool(f) == False + assert mapnik.Expression("not [prop] = true").to_bool(f) == False + assert mapnik.Expression("[prop] = true").to_bool(f) == True + assert mapnik.Expression("[prop] != true").to_bool(f) == False def test_division_by_zero(): @@ -490,13 +464,9 @@ def test_division_by_zero(): f = mapnik.Feature(c, 0) f['a'] = 1 f['b'] = 0 - eq_(expr.evaluate(f), None) + assert expr.evaluate(f) == None -@raises(RuntimeError) def test_invalid_syntax1(): - mapnik.Expression('abs()') - - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + with pytest.raises(RuntimeError): + mapnik.Expression('abs()') diff --git a/test/python_tests/fontset_test.py b/test/python_tests/fontset_test.py index 0baed51fd..3fb01dce0 100644 --- a/test/python_tests/fontset_test.py +++ b/test/python_tests/fontset_test.py @@ -1,47 +1,28 @@ -#!/usr/bin/env python - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_loading_fontset_from_map(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/fontset.xml', True) + mapnik.load_map(m, './test/data/good_maps/fontset.xml', True) fs = m.find_fontset('book-fonts') - eq_(len(fs.names), 2) - eq_(list(fs.names), ['DejaVu Sans Book', 'DejaVu Sans Oblique']) + assert len(fs.names) == 2 + assert list(fs.names) == ['DejaVu Sans Book', 'DejaVu Sans Oblique'] # def test_loading_fontset_from_python(): # m = mapnik.Map(256,256) # fset = mapnik.FontSet('foo') # fset.add_face_name('Comic Sans') # fset.add_face_name('Papyrus') -# eq_(fset.name,'foo') +# assert fset.name == 'foo' # fset.name = 'my-set' -# eq_(fset.name,'my-set') +# assert fset.name == 'my-set' # m.append_fontset('my-set', fset) # sty = mapnik.Style() # rule = mapnik.Rule() # tsym = mapnik.TextSymbolizer() -# eq_(tsym.fontset,None) +# assert tsym.fontset == None # tsym.fontset = fset # rule.symbols.append(tsym) # sty.rules.append(rule) # m.append_style('Style',sty) # serialized_map = mapnik.save_map_to_string(m) -# eq_('fontset-name="my-set"' in serialized_map,True) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) +# assert 'fontset-name="my-set"' in serialized_map == True diff --git a/test/python_tests/geojson_plugin_test.py b/test/python_tests/geojson_plugin_test.py index dfd40acac..557ef242a 100644 --- a/test/python_tests/geojson_plugin_test.py +++ b/test/python_tests/geojson_plugin_test.py @@ -1,104 +1,90 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os - -from nose.tools import assert_almost_equal, eq_ - import mapnik - -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) +import pytest if 'geojson' in mapnik.DatasourceCache.plugin_names(): def test_geojson_init(): ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson') + file='./test/data/json/escaped.geojson') e = ds.envelope() - assert_almost_equal(e.minx, -81.705583, places=7) - assert_almost_equal(e.miny, 41.480573, places=6) - assert_almost_equal(e.maxx, -81.705583, places=5) - assert_almost_equal(e.maxy, 41.480573, places=3) + assert e.minx == pytest.approx(-81.705583, abs=1e-7) + assert e.miny == pytest.approx(41.480573, abs=1e-6) + assert e.maxx == pytest.approx(-81.705583, abs=1e-5) + assert e.maxy == pytest.approx(41.480573, abs=1e-3) def test_geojson_properties(): ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson') + file='./test/data/json/escaped.geojson') f = list(ds.features_at_point(ds.envelope().center()))[0] - eq_(len(ds.fields()), 11) + assert len(ds.fields()) == 11 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson') + file='./test/data/json/escaped.geojson') f = list(ds.all_features())[0] - eq_(len(ds.fields()), 11) + assert len(ds.fields()) == 11 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' def test_large_geojson_properties(): ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson', + file='./test/data/json/escaped.geojson', cache_features=False) f = list(ds.features_at_point(ds.envelope().center()))[0] - eq_(len(ds.fields()), 11) + assert len(ds.fields()) == 11 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson') + file='./test/data/json/escaped.geojson') f = list(ds.all_features())[0] - eq_(len(ds.fields()), 11) + assert len(ds.fields()) == 11 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' def test_geojson_from_in_memory_string(): # will silently fail since it is a geometry and needs to be a featurecollection. @@ -107,21 +93,21 @@ def test_geojson_from_in_memory_string(): ds = mapnik.Datasource( type='geojson', inline='{ "type":"FeatureCollection", "features": [ { "type":"Feature", "properties":{"name":"test"}, "geometry": { "type":"LineString","coordinates":[[0,0],[10,10]] } } ]}') - eq_(len(ds.fields()), 1) + assert len(ds.fields()) == 1 f = list(ds.all_features())[0] desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.LineString) - eq_(f['name'], u'test') + assert desc['geometry_type'] == mapnik.DataGeometryType.LineString + assert f['name'] == u'test' # @raises(RuntimeError) def test_that_nonexistant_query_field_throws(**kwargs): ds = mapnik.Datasource( type='geojson', - file='../data/json/escaped.geojson') - eq_(len(ds.fields()), 11) + file='./test/data/json/escaped.geojson') + assert len(ds.fields()) == 11 # TODO - this sorting is messed up - #eq_(ds.fields(),['name', 'int', 'double', 'description', 'boolean', 'NOM_FR']) - #eq_(ds.field_types(),['str', 'int', 'float', 'str', 'bool', 'str']) + #assert ds.fields(),['name', 'int', 'double', 'description', 'boolean' == 'NOM_FR'] + #assert ds.field_types(),['str', 'int', 'float', 'str', 'bool' == 'str'] # TODO - should geojson plugin throw like others? # query = mapnik.Query(ds.envelope()) # for fld in ds.fields(): @@ -133,13 +119,9 @@ def test_that_nonexistant_query_field_throws(**kwargs): def test_parsing_feature_collection_with_top_level_properties(): ds = mapnik.Datasource( type='geojson', - file='../data/json/feature_collection_level_properties.json') + file='./test/data/json/feature_collection_level_properties.json') f = list(ds.all_features())[0] desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - eq_(f['feat_name'], u'feat_value') - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + assert f['feat_name'] == u'feat_value' diff --git a/test/python_tests/geometry_io_test.py b/test/python_tests/geometry_io_test.py index f1bac0b4e..f24b90198 100644 --- a/test/python_tests/geometry_io_test.py +++ b/test/python_tests/geometry_io_test.py @@ -1,25 +1,12 @@ -# encoding: utf8 - -import os from binascii import unhexlify - -from nose.tools import eq_, assert_raises - import mapnik - -from .utilities import execution_path, run_all - +import pytest try: import json except ImportError: import simplejson as json -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - wkts = [ [mapnik.GeometryType.Point, "POINT(30 10)", @@ -183,20 +170,20 @@ def setup(): def test_path_geo_interface(): geom = mapnik.Geometry.from_wkt('POINT(0 0)') - eq_(geom.__geo_interface__, {u'type': u'Point', u'coordinates': [0, 0]}) + assert geom.__geo_interface__, {u'type': u'Point', u'coordinates': [0 == 0]} def test_valid_wkb_parsing(): count = 0 for wkb in empty_wkbs: geom = mapnik.Geometry.from_wkb(unhexlify(wkb[2])) - eq_(geom.is_empty(), True) - eq_(geom.type(), wkb[0]) + assert geom.is_empty() == True + assert geom.type() == wkb[0] for wkb in wkts: geom = mapnik.Geometry.from_wkb(unhexlify(wkb[2])) - eq_(geom.is_empty(), False) - eq_(geom.type(), wkb[0]) + assert geom.is_empty() == False + assert geom.type() == wkb[0] def test_wkb_parsing_error(): @@ -205,7 +192,7 @@ def test_wkb_parsing_error(): try: geom = mapnik.Geometry.from_wkb(unhexlify(wkb)) # should not get here - eq_(True, False) + assert True == False except: pass assert True @@ -218,8 +205,8 @@ def test_empty_wkb_parsing(): count = 0 for wkb in partially_empty_wkb: geom = mapnik.Geometry.from_wkb(unhexlify(wkb[2])) - eq_(geom.type(), wkb[0]) - eq_(geom.is_empty(), False) + assert geom.type() == wkb[0] + assert geom.is_empty() == False def test_geojson_parsing(): @@ -228,14 +215,14 @@ def test_geojson_parsing(): for j in geojson: count += 1 geometries.append(mapnik.Geometry.from_geojson(j[1])) - eq_(count, len(geometries)) + assert count == len(geometries) def test_geojson_parsing_reversed(): for idx, j in enumerate(geojson_reversed): g1 = mapnik.Geometry.from_geojson(j) g2 = mapnik.Geometry.from_geojson(geojson[idx][1]) - eq_(g1.to_geojson(), g2.to_geojson()) + assert g1.to_geojson() == g2.to_geojson() # http://geojson.org/geojson-spec.html#positions @@ -243,44 +230,44 @@ def test_geojson_parsing_reversed(): def test_geojson_point_positions(): input_json = '{"type":"Point","coordinates":[30,10]}' geom = mapnik.Geometry.from_geojson(input_json) - eq_(geom.to_geojson(), input_json) + assert geom.to_geojson() == input_json # should ignore all but the first two geom = mapnik.Geometry.from_geojson( '{"type":"Point","coordinates":[30,10,50,50,50,50]}') - eq_(geom.to_geojson(), input_json) + assert geom.to_geojson() == input_json def test_geojson_point_positions2(): input_json = '{"type":"LineString","coordinates":[[30,10],[10,30],[40,40]]}' geom = mapnik.Geometry.from_geojson(input_json) - eq_(geom.to_geojson(), input_json) + assert geom.to_geojson() == input_json # should ignore all but the first two geom = mapnik.Geometry.from_geojson( '{"type":"LineString","coordinates":[[30.0,10.0,0,0,0],[10.0,30.0,0,0,0],[40.0,40.0,0,0,0]]}') - eq_(geom.to_geojson(), input_json) + assert geom.to_geojson() == input_json def compare_wkb_from_wkt(wkt, type): geom = mapnik.Geometry.from_wkt(wkt) - eq_(geom.type(), type) + assert geom.type() == type def compare_wkt_to_geojson(idx, wkt, num=None): geom = mapnik.Geometry.from_wkt(wkt) # ensure both have same result gj = geom.to_geojson() - eq_(len(gj) > 1, True) + assert len(gj) > 1 == True a = json.loads(gj) e = json.loads(geojson[idx][1]) - eq_(a, e) + assert a == e def test_wkt_simple(): for wkt in wkts: try: geom = mapnik.Geometry.from_wkt(wkt[1]) - eq_(geom.type(), wkt[0]) + assert geom.type() == wkt[0] except RuntimeError as e: raise RuntimeError('%s %s' % (e, wkt)) @@ -308,7 +295,7 @@ def test_wkt_rounding(): # if precision is set to 15 still fails due to very subtle rounding issues wkt = "POLYGON((7.904185 54.180426,7.89918 54.178168,7.897715 54.182318,7.893565 54.183111,7.890391 54.187567,7.885874 54.19068,7.879893 54.193915,7.894541 54.194647,7.900645 54.19068,7.904185 54.180426))" geom = mapnik.Geometry.from_wkt(wkt) - eq_(geom.type(), mapnik.GeometryType.Polygon) + assert geom.type() == mapnik.GeometryType.Polygon def test_wkt_collection_flattening(): @@ -316,7 +303,7 @@ def test_wkt_collection_flattening(): # currently fails as the MULTIPOLYGON inside will be returned as multiple polygons - not a huge deal - should we worry? #wkt = "GEOMETRYCOLLECTION(POLYGON((1 1,2 1,2 2,1 2,1 1)),MULTIPOLYGON(((40 40,20 45,45 30,40 40)),((20 35,45 20,30 5,10 10,10 30,20 35),(30 20,20 25,20 15,30 20))),LINESTRING(2 3,3 4))" geom = mapnik.Geometry.from_wkt(wkt) - eq_(geom.type(), mapnik.GeometryType.GeometryCollection) + assert geom.type() == mapnik.GeometryType.GeometryCollection def test_creating_feature_from_geojson(): @@ -327,8 +314,8 @@ def test_creating_feature_from_geojson(): } ctx = mapnik.Context() feat = mapnik.Feature.from_geojson(json.dumps(json_feat), ctx) - eq_(feat.id(), 1) - eq_(feat['name'], u'value') + assert feat.id() == 1 + assert feat['name'] == u'value' def test_handling_valid_geojson_empty_geometries(): @@ -336,13 +323,10 @@ def test_handling_valid_geojson_empty_geometries(): geom = mapnik.Geometry.from_geojson(json) out_json = geom.to_geojson() # check round trip - eq_(json.replace(" ",""), out_json) + assert json.replace(" ","") == out_json def test_handling_invalid_geojson_empty_geometries(): - for json in invalid_empty_geometries: - assert_raises(RuntimeError, mapnik.Geometry.from_geojson, json) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + with pytest.raises(RuntimeError): + for json in invalid_empty_geometries: + mapnik.Geometry.from_geojson(json) diff --git a/test/python_tests/grayscale_test.py b/test/python_tests/grayscale_test.py index fad019223..96e33bd5e 100644 --- a/test/python_tests/grayscale_test.py +++ b/test/python_tests/grayscale_test.py @@ -1,16 +1,8 @@ -from nose.tools import eq_ - import mapnik -from .utilities import run_all - - def test_grayscale_conversion(): im = mapnik.Image(2, 2) im.fill(mapnik.Color('white')) im.set_grayscale_to_alpha() pixel = im.get_pixel(0, 0) - eq_((pixel >> 24) & 0xff, 255) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert (pixel >> 24) & 0xff == 255 diff --git a/test/python_tests/image_encoding_speed_test.py b/test/python_tests/image_encoding_speed_test.py index 4d990465d..cafa842b9 100644 --- a/test/python_tests/image_encoding_speed_test.py +++ b/test/python_tests/image_encoding_speed_test.py @@ -1,19 +1,6 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os from timeit import Timer, time - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - combinations = ['png', 'png8', 'png8:m=o', @@ -121,9 +108,3 @@ def aerial_24(): print( 'min: %sms | avg: %sms | total: %sms | len: %s <-- %s' % (min_, avg, elapsed, size, name)) - - -if __name__ == "__main__": - setup() - do_encoding() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) diff --git a/test/python_tests/image_test.py b/test/python_tests/image_test.py index f25ff39c8..ba758b5af 100644 --- a/test/python_tests/image_test.py +++ b/test/python_tests/image_test.py @@ -1,48 +1,30 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -import os -import sys - -from nose.tools import assert_almost_equal, eq_, raises - import mapnik +import pytest -from .utilities import READ_FLAGS, execution_path, get_unique_colors, run_all - -PYTHON3 = sys.version_info[0] == 3 -if PYTHON3: - buffer = memoryview - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - +from .utilities import READ_FLAGS, get_unique_colors def test_type(): im = mapnik.Image(256, 256) - eq_(im.get_type(), mapnik.ImageType.rgba8) + assert im.get_type() == mapnik.ImageType.rgba8 im = mapnik.Image(256, 256, mapnik.ImageType.gray8) - eq_(im.get_type(), mapnik.ImageType.gray8) + assert im.get_type() == mapnik.ImageType.gray8 def test_image_premultiply(): im = mapnik.Image(256, 256) - eq_(im.premultiplied(), False) + assert im.premultiplied() == False # Premultiply should return true that it worked - eq_(im.premultiply(), True) - eq_(im.premultiplied(), True) + assert im.premultiply() == True + assert im.premultiplied() == True # Premultipling again should return false as nothing should happen - eq_(im.premultiply(), False) - eq_(im.premultiplied(), True) + assert im.premultiply() == False + assert im.premultiplied() == True # Demultiply should return true that it worked - eq_(im.demultiply(), True) - eq_(im.premultiplied(), False) + assert im.demultiply() == True + assert im.premultiplied() == False # Demultiply again should not work and return false as it did nothing - eq_(im.demultiply(), False) - eq_(im.premultiplied(), False) + assert im.demultiply() == False + assert im.premultiplied() == False def test_image_premultiply_values(): @@ -50,18 +32,18 @@ def test_image_premultiply_values(): im.fill(mapnik.Color(16, 33, 255, 128)) im.premultiply() c = im.get_pixel(0, 0, True) - eq_(c.r, 8) - eq_(c.g, 17) - eq_(c.b, 128) - eq_(c.a, 128) + assert c.r == 8 + assert c.g == 17 + assert c.b == 128 + assert c.a == 128 im.demultiply() # Do to the nature of this operation the result will not be exactly the # same c = im.get_pixel(0, 0, True) - eq_(c.r, 15) - eq_(c.g, 33) - eq_(c.b, 255) - eq_(c.a, 128) + assert c.r == 15 + assert c.g == 33 + assert c.b == 255 + assert c.a == 128 def test_apply_opacity(): @@ -69,32 +51,32 @@ def test_apply_opacity(): im.fill(mapnik.Color(128, 128, 128, 128)) im.apply_opacity(0.75) c = im.get_pixel(0, 0, True) - eq_(c.r, 128) - eq_(c.g, 128) - eq_(c.b, 128) - eq_(c.a, 96) + assert c.r == 128 + assert c.g == 128 + assert c.b == 128 + assert c.a == 96 def test_background(): im = mapnik.Image(256, 256) - eq_(im.premultiplied(), False) + assert im.premultiplied() == False im.fill(mapnik.Color(32, 64, 125, 128)) - eq_(im.premultiplied(), False) + assert im.premultiplied() == False c = im.get_pixel(0, 0, True) - eq_(c.get_premultiplied(), False) - eq_(c.r, 32) - eq_(c.g, 64) - eq_(c.b, 125) - eq_(c.a, 128) + assert c.get_premultiplied() == False + assert c.r == 32 + assert c.g == 64 + assert c.b == 125 + assert c.a == 128 # Now again with a premultiplied alpha im.fill(mapnik.Color(32, 64, 125, 128, True)) - eq_(im.premultiplied(), True) + assert im.premultiplied() == True c = im.get_pixel(0, 0, True) - eq_(c.get_premultiplied(), True) - eq_(c.r, 32) - eq_(c.g, 64) - eq_(c.b, 125) - eq_(c.a, 128) + assert c.get_premultiplied() == True + assert c.r == 32 + assert c.g == 64 + assert c.b == 125 + assert c.a == 128 def test_set_and_get_pixel(): @@ -106,27 +88,27 @@ def test_set_and_get_pixel(): im.set_pixel(1, 1, c0_pre) # No differences for non premultiplied pixels c1_int = mapnik.Color(im.get_pixel(0, 0)) - eq_(c0.r, c1_int.r) - eq_(c0.g, c1_int.g) - eq_(c0.b, c1_int.b) - eq_(c0.a, c1_int.a) + assert c0.r == c1_int.r + assert c0.g == c1_int.g + assert c0.b == c1_int.b + assert c0.a == c1_int.a c1 = im.get_pixel(0, 0, True) - eq_(c0.r, c1.r) - eq_(c0.g, c1.g) - eq_(c0.b, c1.b) - eq_(c0.a, c1.a) + assert c0.r == c1.r + assert c0.g == c1.g + assert c0.b == c1.b + assert c0.a == c1.a # The premultiplied Color should be demultiplied before being applied. c0_pre.demultiply() c1_int = mapnik.Color(im.get_pixel(1, 1)) - eq_(c0_pre.r, c1_int.r) - eq_(c0_pre.g, c1_int.g) - eq_(c0_pre.b, c1_int.b) - eq_(c0_pre.a, c1_int.a) + assert c0_pre.r == c1_int.r + assert c0_pre.g == c1_int.g + assert c0_pre.b == c1_int.b + assert c0_pre.a == c1_int.a c1 = im.get_pixel(1, 1, True) - eq_(c0_pre.r, c1.r) - eq_(c0_pre.g, c1.g) - eq_(c0_pre.b, c1.b) - eq_(c0_pre.a, c1.a) + assert c0_pre.r == c1.r + assert c0_pre.g == c1.g + assert c0_pre.b == c1.b + assert c0_pre.a == c1.a # Now create a new image that is premultiplied im = mapnik.Image(256, 256, mapnik.ImageType.rgba8, True, True) @@ -138,26 +120,26 @@ def test_set_and_get_pixel(): # premultiply c0 c0.premultiply() c1_int = mapnik.Color(im.get_pixel(0, 0)) - eq_(c0.r, c1_int.r) - eq_(c0.g, c1_int.g) - eq_(c0.b, c1_int.b) - eq_(c0.a, c1_int.a) + assert c0.r == c1_int.r + assert c0.g == c1_int.g + assert c0.b == c1_int.b + assert c0.a == c1_int.a c1 = im.get_pixel(0, 0, True) - eq_(c0.r, c1.r) - eq_(c0.g, c1.g) - eq_(c0.b, c1.b) - eq_(c0.a, c1.a) + assert c0.r == c1.r + assert c0.g == c1.g + assert c0.b == c1.b + assert c0.a == c1.a # The premultiplied Color should be the same though c1_int = mapnik.Color(im.get_pixel(1, 1)) - eq_(c0_pre.r, c1_int.r) - eq_(c0_pre.g, c1_int.g) - eq_(c0_pre.b, c1_int.b) - eq_(c0_pre.a, c1_int.a) + assert c0_pre.r == c1_int.r + assert c0_pre.g == c1_int.g + assert c0_pre.b == c1_int.b + assert c0_pre.a == c1_int.a c1 = im.get_pixel(1, 1, True) - eq_(c0_pre.r, c1.r) - eq_(c0_pre.g, c1.g) - eq_(c0_pre.b, c1.b) - eq_(c0_pre.a, c1.a) + assert c0_pre.r == c1.r + assert c0_pre.g == c1.g + assert c0_pre.b == c1.b + assert c0_pre.a == c1.a def test_pixel_gray8(): @@ -165,9 +147,9 @@ def test_pixel_gray8(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 def test_pixel_gray8s(): @@ -175,9 +157,9 @@ def test_pixel_gray8s(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == -v def test_pixel_gray16(): @@ -185,9 +167,9 @@ def test_pixel_gray16(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 def test_pixel_gray16s(): @@ -195,9 +177,9 @@ def test_pixel_gray16s(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == -v def test_pixel_gray32(): @@ -205,9 +187,9 @@ def test_pixel_gray32(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 def test_pixel_gray32s(): @@ -215,9 +197,9 @@ def test_pixel_gray32s(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == -v def test_pixel_gray64(): @@ -225,9 +207,9 @@ def test_pixel_gray64(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 def test_pixel_gray64s(): @@ -235,9 +217,9 @@ def test_pixel_gray64s(): val_list = range(20) for v in val_list: im.set_pixel(0, 0, v) - eq_(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == v im.set_pixel(0, 0, -v) - eq_(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == -v def test_pixel_floats(): @@ -245,9 +227,9 @@ def test_pixel_floats(): val_list = [0.9, 0.99, 0.999, 0.9999, 0.99999, 1, 1.0001, 1.001, 1.01, 1.1] for v in val_list: im.set_pixel(0, 0, v) - assert_almost_equal(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == pytest.approx(v) im.set_pixel(0, 0, -v) - assert_almost_equal(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == pytest.approx(-v) def test_pixel_doubles(): @@ -255,80 +237,80 @@ def test_pixel_doubles(): val_list = [0.9, 0.99, 0.999, 0.9999, 0.99999, 1, 1.0001, 1.001, 1.01, 1.1] for v in val_list: im.set_pixel(0, 0, v) - assert_almost_equal(im.get_pixel(0, 0), v) + assert im.get_pixel(0, 0) == pytest.approx(v) im.set_pixel(0, 0, -v) - assert_almost_equal(im.get_pixel(0, 0), -v) + assert im.get_pixel(0, 0) == pytest.approx(-v) def test_pixel_overflow(): im = mapnik.Image(4, 4, mapnik.ImageType.gray8) im.set_pixel(0, 0, 256) - eq_(im.get_pixel(0, 0), 255) + assert im.get_pixel(0, 0) == 255 def test_pixel_underflow(): im = mapnik.Image(4, 4, mapnik.ImageType.gray8) im.set_pixel(0, 0, -1) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 im = mapnik.Image(4, 4, mapnik.ImageType.gray16) im.set_pixel(0, 0, -1) - eq_(im.get_pixel(0, 0), 0) + assert im.get_pixel(0, 0) == 0 -@raises(IndexError) def test_set_pixel_out_of_range_1(): - im = mapnik.Image(4, 4) - c = mapnik.Color('blue') - im.set_pixel(5, 5, c) + with pytest.raises(IndexError): + im = mapnik.Image(4, 4) + c = mapnik.Color('blue') + im.set_pixel(5, 5, c) -@raises(OverflowError) def test_set_pixel_out_of_range_2(): - im = mapnik.Image(4, 4) - c = mapnik.Color('blue') - im.set_pixel(-1, 1, c) + with pytest.raises(OverflowError): + im = mapnik.Image(4, 4) + c = mapnik.Color('blue') + im.set_pixel(-1, 1, c) -@raises(IndexError) def test_get_pixel_out_of_range_1(): - im = mapnik.Image(4, 4) - c = im.get_pixel(5, 5) + with pytest.raises(IndexError): + im = mapnik.Image(4, 4) + c = im.get_pixel(5, 5) -@raises(OverflowError) def test_get_pixel_out_of_range_2(): - im = mapnik.Image(4, 4) - c = im.get_pixel(-1, 1) + with pytest.raises(OverflowError): + im = mapnik.Image(4, 4) + c = im.get_pixel(-1, 1) -@raises(IndexError) def test_get_pixel_color_out_of_range_1(): - im = mapnik.Image(4, 4) - c = im.get_pixel(5, 5, True) + with pytest.raises(IndexError): + im = mapnik.Image(4, 4) + c = im.get_pixel(5, 5, True) -@raises(OverflowError) def test_get_pixel_color_out_of_range_2(): - im = mapnik.Image(4, 4) - c = im.get_pixel(-1, 1, True) + with pytest.raises(OverflowError): + im = mapnik.Image(4, 4) + c = im.get_pixel(-1, 1, True) def test_set_color_to_alpha(): im = mapnik.Image(256, 256) im.fill(mapnik.Color('rgba(12,12,12,255)')) - eq_(get_unique_colors(im), ['rgba(12,12,12,255)']) + assert get_unique_colors(im), ['rgba(12,12,12 == 255)'] im.set_color_to_alpha(mapnik.Color('rgba(12,12,12,0)')) - eq_(get_unique_colors(im), ['rgba(0,0,0,0)']) + assert get_unique_colors(im), ['rgba(0,0,0 == 0)'] -@raises(RuntimeError) def test_negative_image_dimensions(): - # TODO - this may have regressed in - # https://github.com/mapnik/mapnik/commit/4f3521ac24b61fc8ae8fd344a16dc3a5fdf15af7 - im = mapnik.Image(-40, 40) - # should not get here - eq_(im.width(), 0) - eq_(im.height(), 0) + with pytest.raises(RuntimeError): + # TODO - this may have regressed in + # https://github.com/mapnik/mapnik/commit/4f3521ac24b61fc8ae8fd344a16dc3a5fdf15af7 + im = mapnik.Image(-40, 40) + # should not get here + assert im.width() == 0 + assert im.height() == 0 def test_jpeg_round_trip(): @@ -339,14 +321,14 @@ def test_jpeg_round_trip(): im2 = mapnik.Image.open(filepath) with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) - eq_(len(im.tostring()), len(im2.tostring())) - eq_(len(im.tostring('jpeg')), len(im2.tostring('jpeg'))) - eq_(len(im.tostring()), len(im3.tostring())) - eq_(len(im.tostring('jpeg')), len(im3.tostring('jpeg'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() + assert len(im.tostring()) == len(im2.tostring()) + assert len(im.tostring('jpeg')) == len(im2.tostring('jpeg')) + assert len(im.tostring()) == len(im3.tostring()) + assert len(im.tostring('jpeg')) == len(im3.tostring('jpeg')) def test_png_round_trip(): @@ -357,35 +339,31 @@ def test_png_round_trip(): im2 = mapnik.Image.open(filepath) with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) - eq_(len(im.tostring()), len(im2.tostring())) - eq_(len(im.tostring('png')), len(im2.tostring('png'))) - eq_(len(im.tostring('png8')), len(im2.tostring('png8'))) - eq_(len(im.tostring()), len(im3.tostring())) - eq_(len(im.tostring('png')), len(im3.tostring('png'))) - eq_(len(im.tostring('png8')), len(im3.tostring('png8'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() + assert len(im.tostring()) == len(im2.tostring()) + assert len(im.tostring('png')) == len(im2.tostring('png')) + assert len(im.tostring('png8')) == len(im2.tostring('png8')) + assert len(im.tostring()) == len(im3.tostring()) + assert len(im.tostring('png')) == len(im3.tostring('png')) + assert len(im.tostring('png8')) == len(im3.tostring('png8')) def test_image_open_from_string(): - filepath = '../data/images/dummy.png' + filepath = './test/data/images/dummy.png' im1 = mapnik.Image.open(filepath) with open(filepath, READ_FLAGS) as f: im2 = mapnik.Image.fromstring(f.read()) - eq_(im1.width(), im2.width()) + assert im1.width() == im2.width() length = len(im1.tostring()) - eq_(length, len(im2.tostring())) - eq_(len(mapnik.Image.fromstring(im1.tostring('png')).tostring()), length) - eq_(len(mapnik.Image.fromstring(im1.tostring('jpeg')).tostring()), length) - eq_(len(mapnik.Image.frombuffer(buffer(im1.tostring('png'))).tostring()), length) - eq_(len(mapnik.Image.frombuffer(buffer(im1.tostring('jpeg'))).tostring()), length) + assert length == len(im2.tostring()) + assert len(mapnik.Image.fromstring(im1.tostring('png')).tostring()) == length + assert len(mapnik.Image.fromstring(im1.tostring('jpeg')).tostring()) == length + assert len(mapnik.Image.frombuffer(memoryview(im1.tostring('png'))).tostring()) == length + assert len(mapnik.Image.frombuffer(memoryview(im1.tostring('jpeg'))).tostring()) == length # TODO - https://github.com/mapnik/mapnik/issues/1831 - eq_(len(mapnik.Image.fromstring(im1.tostring('tiff')).tostring()), length) - eq_(len(mapnik.Image.frombuffer(buffer(im1.tostring('tiff'))).tostring()), length) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert len(mapnik.Image.fromstring(im1.tostring('tiff')).tostring()) == length + assert len(mapnik.Image.frombuffer(memoryview(im1.tostring('tiff'))).tostring()) == length diff --git a/test/python_tests/image_tiff_test.py b/test/python_tests/image_tiff_test.py index b1915c111..c5fcc395f 100644 --- a/test/python_tests/image_tiff_test.py +++ b/test/python_tests/image_tiff_test.py @@ -1,26 +1,11 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - import hashlib -import os - -from nose.tools import assert_not_equal, eq_ - import mapnik -from .utilities import READ_FLAGS, execution_path, run_all - +from .utilities import READ_FLAGS def hashstr(var): return hashlib.md5(var).hexdigest() - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_tiff_round_trip_scanline(): filepath = '/tmp/mapnik-tiff-io-scanline.tiff' im = mapnik.Image(255, 267) @@ -30,26 +15,21 @@ def test_tiff_round_trip_scanline(): im2 = mapnik.Image.open(filepath) with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) - eq_(hashstr(im.tostring()), org_str) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() + assert hashstr(im.tostring()) == org_str # This won't be the same the first time around because the im is not # premultiplied and im2 is - assert_not_equal(hashstr(im.tostring()), hashstr(im2.tostring())) - assert_not_equal( - hashstr( - im.tostring('tiff:method=scanline')), hashstr( - im2.tostring('tiff:method=scanline'))) + assert not hashstr(im.tostring()) == hashstr(im2.tostring()) + assert not hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) # Now premultiply im.premultiply() - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=scanline')), - hashstr(im2.tostring('tiff:method=scanline'))) - eq_(hashstr(im2.tostring()), hashstr(im3.tostring())) - eq_(hashstr(im2.tostring('tiff:method=scanline')), - hashstr(im3.tostring('tiff:method=scanline'))) + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) + assert hashstr(im2.tostring()) == hashstr(im3.tostring()) + assert hashstr(im2.tostring('tiff:method=scanline')) == hashstr(im3.tostring('tiff:method=scanline')) def test_tiff_round_trip_stripped(): @@ -62,27 +42,22 @@ def test_tiff_round_trip_stripped(): im2.save('/tmp/mapnik-tiff-io-stripped2.tiff', 'tiff:method=stripped') with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() # Because one will end up with UNASSOC alpha tag which internally the TIFF reader will premultiply, the first to string will not be the same due to the # difference in tags. - assert_not_equal(hashstr(im.tostring()), hashstr(im2.tostring())) - assert_not_equal( - hashstr( - im.tostring('tiff:method=stripped')), hashstr( - im2.tostring('tiff:method=stripped'))) + assert not hashstr(im.tostring()) == hashstr(im2.tostring()) + assert not hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) # Now if we premultiply they will be exactly the same im.premultiply() - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=stripped')), - hashstr(im2.tostring('tiff:method=stripped'))) - eq_(hashstr(im2.tostring()), hashstr(im3.tostring())) + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) + assert hashstr(im2.tostring()) == hashstr(im3.tostring()) # Both of these started out premultiplied, so this round trip should be # exactly the same! - eq_(hashstr(im2.tostring('tiff:method=stripped')), - hashstr(im3.tostring('tiff:method=stripped'))) + assert hashstr(im2.tostring('tiff:method=stripped')) == hashstr(im3.tostring('tiff:method=stripped')) def test_tiff_round_trip_rows_stripped(): @@ -91,42 +66,38 @@ def test_tiff_round_trip_rows_stripped(): im = mapnik.Image(255, 267) im.fill(mapnik.Color('rgba(12,255,128,.5)')) c = im.get_pixel(0, 0, True) - eq_(c.r, 12) - eq_(c.g, 255) - eq_(c.b, 128) - eq_(c.a, 128) - eq_(c.get_premultiplied(), False) + assert c.r == 12 + assert c.g == 255 + assert c.b == 128 + assert c.a == 128 + assert c.get_premultiplied() == False im.save(filepath, 'tiff:method=stripped:rows_per_strip=8') im2 = mapnik.Image.open(filepath) c2 = im2.get_pixel(0, 0, True) - eq_(c2.r, 6) - eq_(c2.g, 128) - eq_(c2.b, 64) - eq_(c2.a, 128) - eq_(c2.get_premultiplied(), True) + assert c2.r == 6 + assert c2.g == 128 + assert c2.b == 64 + assert c2.a == 128 + assert c2.get_premultiplied() == True im2.save(filepath2, 'tiff:method=stripped:rows_per_strip=8') with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() # Because one will end up with UNASSOC alpha tag which internally the TIFF reader will premultiply, the first to string will not be the same due to the # difference in tags. - assert_not_equal(hashstr(im.tostring()), hashstr(im2.tostring())) - assert_not_equal( - hashstr( - im.tostring('tiff:method=stripped:rows_per_strip=8')), hashstr( - im2.tostring('tiff:method=stripped:rows_per_strip=8'))) + assert not hashstr(im.tostring()) == hashstr(im2.tostring()) + assert not hashstr(im.tostring('tiff:method=stripped:rows_per_strip=8')) == hashstr( + im2.tostring('tiff:method=stripped:rows_per_strip=8')) # Now premultiply the first image and they will be the same! im.premultiply() - eq_(hashstr(im.tostring('tiff:method=stripped:rows_per_strip=8')), - hashstr(im2.tostring('tiff:method=stripped:rows_per_strip=8'))) - eq_(hashstr(im2.tostring()), hashstr(im3.tostring())) + assert hashstr(im.tostring('tiff:method=stripped:rows_per_strip=8')) == hashstr(im2.tostring('tiff:method=stripped:rows_per_strip=8')) + assert hashstr(im2.tostring()) == hashstr(im3.tostring()) # Both of these started out premultiplied, so this round trip should be # exactly the same! - eq_(hashstr(im2.tostring('tiff:method=stripped:rows_per_strip=8')), - hashstr(im3.tostring('tiff:method=stripped:rows_per_strip=8'))) + assert hashstr(im2.tostring('tiff:method=stripped:rows_per_strip=8')) == hashstr(im3.tostring('tiff:method=stripped:rows_per_strip=8')) def test_tiff_round_trip_buffered_tiled(): @@ -136,44 +107,40 @@ def test_tiff_round_trip_buffered_tiled(): im = mapnik.Image(255, 267) im.fill(mapnik.Color('rgba(33,255,128,.5)')) c = im.get_pixel(0, 0, True) - eq_(c.r, 33) - eq_(c.g, 255) - eq_(c.b, 128) - eq_(c.a, 128) - eq_(c.get_premultiplied(), False) + assert c.r == 33 + assert c.g == 255 + assert c.b == 128 + assert c.a == 128 + assert not c.get_premultiplied() im.save(filepath, 'tiff:method=tiled:tile_width=32:tile_height=32') im2 = mapnik.Image.open(filepath) c2 = im2.get_pixel(0, 0, True) - eq_(c2.r, 17) - eq_(c2.g, 128) - eq_(c2.b, 64) - eq_(c2.a, 128) - eq_(c2.get_premultiplied(), True) + assert c2.r == 17 + assert c2.g == 128 + assert c2.b == 64 + assert c2.a == 128 + assert c2.get_premultiplied() with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) im2.save(filepath2, 'tiff:method=tiled:tile_width=32:tile_height=32') im3.save(filepath3, 'tiff:method=tiled:tile_width=32:tile_height=32') - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() # Because one will end up with UNASSOC alpha tag which internally the TIFF reader will premultiply, the first to string will not be the same due to the # difference in tags. - assert_not_equal(hashstr(im.tostring()), hashstr(im2.tostring())) - assert_not_equal( - hashstr( - im.tostring('tiff:method=tiled:tile_width=32:tile_height=32')), hashstr( - im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32'))) + assert not hashstr(im.tostring()) == hashstr(im2.tostring()) + assert not hashstr(im.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) == hashstr( + im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) # Now premultiply the first image and they should be the same im.premultiply() - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled:tile_width=32:tile_height=32')), - hashstr(im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32'))) - eq_(hashstr(im2.tostring()), hashstr(im3.tostring())) + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) == hashstr(im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) + assert hashstr(im2.tostring()) == hashstr(im3.tostring()) # Both of these started out premultiplied, so this round trip should be # exactly the same! - eq_(hashstr(im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32')), - hashstr(im3.tostring('tiff:method=tiled:tile_width=32:tile_height=32'))) + assert hashstr(im2.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) == hashstr(im3.tostring('tiff:method=tiled:tile_width=32:tile_height=32')) def test_tiff_round_trip_tiled(): @@ -184,235 +151,199 @@ def test_tiff_round_trip_tiled(): im2 = mapnik.Image.open(filepath) with open(filepath, READ_FLAGS) as f: im3 = mapnik.Image.fromstring(f.read()) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(im.width(), im3.width()) - eq_(im.height(), im3.height()) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert im.width() == im3.width() + assert im.height() == im3.height() # Because one will end up with UNASSOC alpha tag which internally the TIFF reader will premultiply, the first to string will not be the same due to the # difference in tags. - assert_not_equal(hashstr(im.tostring()), hashstr(im2.tostring())) - assert_not_equal( - hashstr( - im.tostring('tiff:method=tiled')), hashstr( - im2.tostring('tiff:method=tiled'))) + assert not hashstr(im.tostring()) == hashstr(im2.tostring()) + assert not hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) # Now premultiply the first image and they will be exactly the same. im.premultiply() - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled')), - hashstr(im2.tostring('tiff:method=tiled'))) - eq_(hashstr(im2.tostring()), hashstr(im3.tostring())) + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) + assert hashstr(im2.tostring()) == hashstr(im3.tostring()) # Both of these started out premultiplied, so this round trip should be # exactly the same! - eq_(hashstr(im2.tostring('tiff:method=tiled')), - hashstr(im3.tostring('tiff:method=tiled'))) + assert hashstr(im2.tostring('tiff:method=tiled')) == hashstr(im3.tostring('tiff:method=tiled')) def test_tiff_rgb8_compare(): - filepath1 = '../data/tiff/ndvi_256x256_rgb8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_rgb8_striped.tif' filepath2 = '/tmp/mapnik-tiff-rgb8.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff')), hashstr(im2.tostring('tiff'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff')) == hashstr(im2.tostring('tiff')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")) def test_tiff_rgba8_compare_scanline(): - filepath1 = '../data/tiff/ndvi_256x256_rgba8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_rgba8_striped.tif' filepath2 = '/tmp/mapnik-tiff-rgba8-scanline.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=scanline') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=scanline')), - hashstr(im2.tostring('tiff:method=scanline'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")) def test_tiff_rgba8_compare_stripped(): - filepath1 = '../data/tiff/ndvi_256x256_rgba8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_rgba8_striped.tif' filepath2 = '/tmp/mapnik-tiff-rgba8-stripped.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=stripped') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=stripped')), - hashstr(im2.tostring('tiff:method=stripped'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")) def test_tiff_rgba8_compare_tiled(): - filepath1 = '../data/tiff/ndvi_256x256_rgba8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_rgba8_striped.tif' filepath2 = '/tmp/mapnik-tiff-rgba8-tiled.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=tiled') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled')), - hashstr(im2.tostring('tiff:method=tiled'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.rgba8).tostring("tiff")) def test_tiff_gray8_compare_scanline(): - filepath1 = '../data/tiff/ndvi_256x256_gray8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray8_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray8-scanline.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=scanline') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=scanline')), - hashstr(im2.tostring('tiff:method=scanline'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")), True) - + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")) def test_tiff_gray8_compare_stripped(): - filepath1 = '../data/tiff/ndvi_256x256_gray8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray8_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray8-stripped.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=stripped') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=stripped')), - hashstr(im2.tostring('tiff:method=stripped'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")) def test_tiff_gray8_compare_tiled(): - filepath1 = '../data/tiff/ndvi_256x256_gray8_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray8_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray8-tiled.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=tiled') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled')), - hashstr(im2.tostring('tiff:method=tiled'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray8).tostring("tiff")) def test_tiff_gray16_compare_scanline(): - filepath1 = '../data/tiff/ndvi_256x256_gray16_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray16_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray16-scanline.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=scanline') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=scanline')), - hashstr(im2.tostring('tiff:method=scanline'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")), True) - + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")) def test_tiff_gray16_compare_stripped(): - filepath1 = '../data/tiff/ndvi_256x256_gray16_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray16_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray16-stripped.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=stripped') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=stripped')), - hashstr(im2.tostring('tiff:method=stripped'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")) def test_tiff_gray16_compare_tiled(): - filepath1 = '../data/tiff/ndvi_256x256_gray16_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray16_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray16-tiled.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=tiled') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled')), - hashstr(im2.tostring('tiff:method=tiled'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image( - im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray16).tostring("tiff")) def test_tiff_gray32f_compare_scanline(): - filepath1 = '../data/tiff/ndvi_256x256_gray32f_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray32f_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray32f-scanline.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=scanline') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=scanline')), - hashstr(im2.tostring('tiff:method=scanline'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=scanline')) == hashstr(im2.tostring('tiff:method=scanline')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), - im.height(), mapnik.ImageType.gray32f).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray32f).tostring("tiff")) def test_tiff_gray32f_compare_stripped(): - filepath1 = '../data/tiff/ndvi_256x256_gray32f_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray32f_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray32f-stripped.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=stripped') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=stripped')), - hashstr(im2.tostring('tiff:method=stripped'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=stripped')) == hashstr(im2.tostring('tiff:method=stripped')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), - im.height(), mapnik.ImageType.gray32f).tostring("tiff")), True) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray32f).tostring("tiff")) def test_tiff_gray32f_compare_tiled(): - filepath1 = '../data/tiff/ndvi_256x256_gray32f_striped.tif' + filepath1 = './test/data/tiff/ndvi_256x256_gray32f_striped.tif' filepath2 = '/tmp/mapnik-tiff-gray32f-tiled.tiff' im = mapnik.Image.open(filepath1) im.save(filepath2, 'tiff:method=tiled') im2 = mapnik.Image.open(filepath2) - eq_(im.width(), im2.width()) - eq_(im.height(), im2.height()) - eq_(hashstr(im.tostring()), hashstr(im2.tostring())) - eq_(hashstr(im.tostring('tiff:method=tiled')), - hashstr(im2.tostring('tiff:method=tiled'))) + assert im.width() == im2.width() + assert im.height() == im2.height() + assert hashstr(im.tostring()) == hashstr(im2.tostring()) + assert hashstr(im.tostring('tiff:method=tiled')) == hashstr(im2.tostring('tiff:method=tiled')) # should not be a blank image - eq_(hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), - im.height(), mapnik.ImageType.gray32f).tostring("tiff")), True) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert hashstr(im.tostring("tiff")) != hashstr(mapnik.Image(im.width(), im.height(), mapnik.ImageType.gray32f).tostring("tiff")) diff --git a/test/python_tests/images/pycairo/cairo-cairo-expected.pdf b/test/python_tests/images/pycairo/cairo-cairo-expected.pdf index 220a9b210..2d2d0dad9 100644 Binary files a/test/python_tests/images/pycairo/cairo-cairo-expected.pdf and b/test/python_tests/images/pycairo/cairo-cairo-expected.pdf differ diff --git a/test/python_tests/introspection_test.py b/test/python_tests/introspection_test.py index 0c1e39dd2..215be7d3f 100644 --- a/test/python_tests/introspection_test.py +++ b/test/python_tests/introspection_test.py @@ -1,36 +1,21 @@ -#!/usr/bin/env python - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_introspect_symbolizers(): # create a symbolizer p = mapnik.PointSymbolizer() - p.file = "../data/images/dummy.png" + p.file = "./test/data/images/dummy.png" p.allow_overlap = True p.opacity = 0.5 - eq_(p.allow_overlap, True) - eq_(p.opacity, 0.5) - eq_(p.filename, '../data/images/dummy.png') + assert p.allow_overlap == True + assert p.opacity == 0.5 + assert p.filename == './test/data/images/dummy.png' # make sure the defaults # are what we think they are - eq_(p.allow_overlap, True) - eq_(p.opacity, 0.5) - eq_(p.filename, '../data/images/dummy.png') + assert p.allow_overlap == True + assert p.opacity == 0.5 + assert p.filename == './test/data/images/dummy.png' # contruct objects to hold it r = mapnik.Rule() @@ -46,20 +31,16 @@ def test_introspect_symbolizers(): s2 = m.find_style('s') rules = s2.rules - eq_(len(rules), 1) + assert len(rules) == 1 r2 = rules[0] syms = r2.symbols - eq_(len(syms), 1) + assert len(syms) == 1 # TODO here, we can do... sym = syms[0] p2 = sym.extract() assert isinstance(p2, mapnik.PointSymbolizer) - eq_(p2.allow_overlap, True) - eq_(p2.opacity, 0.5) - eq_(p2.filename, '../data/images/dummy.png') - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert p2.allow_overlap == True + assert p2.opacity == 0.5 + assert p2.filename == './test/data/images/dummy.png' diff --git a/test/python_tests/json_feature_properties_test.py b/test/python_tests/json_feature_properties_test.py index 41557455c..10ae884d8 100644 --- a/test/python_tests/json_feature_properties_test.py +++ b/test/python_tests/json_feature_properties_test.py @@ -1,11 +1,4 @@ -# encoding: utf8 - -from nose.tools import eq_ - import mapnik - -from .utilities import run_all - try: import json except ImportError: @@ -83,30 +76,20 @@ ctx = mapnik.Context() ctx.push('name') - def test_char_escaping(): for char in chars: feat = mapnik.Feature(ctx, 1) expected = char['test'] feat["name"] = expected - eq_(feat["name"], expected) + assert feat["name"] == expected # confirm the python json module # is working as we would expect pyjson2 = json.loads(char['json']) - eq_(pyjson2['properties']['name'], expected) + assert pyjson2['properties']['name'] == expected # confirm our behavior is the same as python json module # for the original string geojson_feat_string = feat.to_geojson() - eq_( - geojson_feat_string, - char['json'], - "Mapnik's json escaping is not to spec: actual(%s) and expected(%s) for %s" % - (geojson_feat_string, - char['json'], - char['name'])) + assert geojson_feat_string == char['json'], "Mapnik's json escaping is not to spec: actual(%s) and expected(%s) for %s" % (geojson_feat_string, char['json'], char['name']) # and the round tripped string pyjson = json.loads(geojson_feat_string) - eq_(pyjson['properties']['name'], expected) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert pyjson['properties']['name'] == expected diff --git a/test/python_tests/layer_buffer_size_test.py b/test/python_tests/layer_buffer_size_test.py index 30417a367..093fe7221 100644 --- a/test/python_tests/layer_buffer_size_test.py +++ b/test/python_tests/layer_buffer_size_test.py @@ -1,18 +1,5 @@ -# coding=utf8 -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - if 'sqlite' in mapnik.DatasourceCache.plugin_names(): # the negative buffer on the layer should @@ -20,23 +7,16 @@ def setup(): # only one point to be rendered in the map def test_layer_buffer_size_1(): m = mapnik.Map(512, 512) - eq_(m.buffer_size, 0) - mapnik.load_map(m, '../data/good_maps/layer_buffer_size_reduction.xml') - eq_(m.buffer_size, 256) - eq_(m.layers[0].buffer_size, -150) + assert m.buffer_size == 0 + mapnik.load_map(m, './test/data/good_maps/layer_buffer_size_reduction.xml') + assert m.buffer_size == 256 + assert m.layers[0].buffer_size == -150 m.zoom_all() im = mapnik.Image(m.width, m.height) mapnik.render(m, im) actual = '/tmp/mapnik-layer-buffer-size.png' - expected = 'images/support/mapnik-layer-buffer-size.png' + expected = './test/python_tests/images/support/mapnik-layer-buffer-size.png' im.save(actual, "png32") expected_im = mapnik.Image.open(expected) - eq_(im.tostring('png32'), - expected_im.tostring('png32'), - 'failed comparing actual (%s) and expected (%s)' % (actual, - 'tests/python_tests/' + expected)) - - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert im.tostring('png32') == expected_im.tostring('png32'),'failed comparing actual (%s) and expected (%s)' % (actual, + 'tests/python_tests/' + expected) diff --git a/test/python_tests/layer_modification_test.py b/test/python_tests/layer_modification_test.py index 373a57618..37ac73ed1 100644 --- a/test/python_tests/layer_modification_test.py +++ b/test/python_tests/layer_modification_test.py @@ -1,20 +1,5 @@ -#!/usr/bin/env python - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_adding_datasource_to_layer(): map_string = ''' @@ -25,7 +10,7 @@ def test_adding_datasource_to_layer(): @@ -39,9 +24,9 @@ def test_adding_datasource_to_layer(): mapnik.load_map_from_string(m, map_string) # validate it loaded fine - eq_(m.layers[0].styles[0], 'world_borders_style') - eq_(m.layers[0].styles[1], 'point_style') - eq_(len(m.layers), 1) + assert m.layers[0].styles[0] == 'world_borders_style' + assert m.layers[0].styles[1] == 'point_style' + assert len(m.layers) == 1 # also assign a variable reference to that layer # below we will test that this variable references @@ -49,35 +34,29 @@ def test_adding_datasource_to_layer(): lyr = m.layers[0] # ensure that there was no datasource for the layer... - eq_(m.layers[0].datasource, None) - eq_(lyr.datasource, None) + assert m.layers[0].datasource == None + assert lyr.datasource == None # also note that since the srs was black it defaulted to wgs84 - eq_(m.layers[0].srs, - 'epsg:4326') - eq_(lyr.srs, 'epsg:4326') + assert m.layers[0].srs == 'epsg:4326' + assert lyr.srs == 'epsg:4326' # now add a datasource one... - ds = mapnik.Shapefile(file='../data/shp/world_merc.shp') + ds = mapnik.Shapefile(file='./test/data/shp/world_merc.shp') m.layers[0].datasource = ds # now ensure it is attached - eq_(m.layers[0].datasource.describe()['name'], "shape") - eq_(lyr.datasource.describe()['name'], "shape") + assert m.layers[0].datasource.describe()['name'] == "shape" + assert lyr.datasource.describe()['name'] == "shape" # and since we have now added a shapefile in spherical mercator, adjust # the projection lyr.srs = '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs' # test that assignment - eq_(m.layers[ - 0].srs, '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs') - eq_(lyr.srs, '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs') + assert m.layers[0].srs == '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs' + assert lyr.srs == '+proj=merc +lon_0=0 +lat_ts=0 +x_0=0 +y_0=0 +ellps=WGS84 +datum=WGS84 +units=m +no_defs' except RuntimeError as e: # only test datasources that we have installed if not 'Could not create datasource' in str(e): raise RuntimeError(e) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) diff --git a/test/python_tests/layer_test.py b/test/python_tests/layer_test.py index f096e2589..e8652bbc0 100644 --- a/test/python_tests/layer_test.py +++ b/test/python_tests/layer_test.py @@ -1,33 +1,21 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- - -from nose.tools import eq_ - import mapnik -from .utilities import run_all - - # Map initialization - def test_layer_init(): l = mapnik.Layer('test') - eq_(l.name, 'test') - eq_(l.srs, 'epsg:4326') - eq_(l.envelope(), mapnik.Box2d()) - eq_(l.clear_label_cache, False) - eq_(l.cache_features, False) - eq_(l.visible(1), True) - eq_(l.active, True) - eq_(l.datasource, None) - eq_(l.queryable, False) - eq_(l.minimum_scale_denominator, 0.0) - eq_(l.maximum_scale_denominator > 1e+6, True) - eq_(l.group_by, "") - eq_(l.maximum_extent, None) - eq_(l.buffer_size, None) - eq_(len(l.styles), 0) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert l.name == 'test' + assert l.srs == 'epsg:4326' + assert l.envelope() == mapnik.Box2d() + assert not l.clear_label_cache + assert not l.cache_features + assert l.visible(1) + assert l.active + assert l.datasource == None + assert not l.queryable + assert l.minimum_scale_denominator == 0.0 + assert l.maximum_scale_denominator > 1e+6 + assert l.group_by == "" + assert l.maximum_extent == None + assert l.buffer_size == None + assert len(l.styles) == 0 diff --git a/test/python_tests/load_map_test.py b/test/python_tests/load_map_test.py index ea0b5ccd8..85d23f8ac 100644 --- a/test/python_tests/load_map_test.py +++ b/test/python_tests/load_map_test.py @@ -1,31 +1,11 @@ -#!/usr/bin/env python - import glob -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - default_logging_severity = mapnik.logger.get_severity() - -def setup(): - # make the tests silent to suppress unsupported params from harfbuzz tests - # TODO: remove this after harfbuzz branch merges - mapnik.logger.set_severity(getattr(mapnik.severity_type, "None")) - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def teardown(): mapnik.logger.set_severity(default_logging_severity) - def test_broken_files(): default_logging_severity = mapnik.logger.get_severity() mapnik.logger.set_severity(getattr(mapnik.severity_type, "None")) @@ -44,7 +24,7 @@ def test_broken_files(): filename) except RuntimeError: pass - eq_(len(failures), 0, '\n' + '\n'.join(failures)) + assert len(failures) == 0, '\n' + '\n'.join(failures) mapnik.logger.set_severity(default_logging_severity) @@ -75,7 +55,7 @@ def test_can_parse_xml_with_deprecated_properties(): failures.append( 'Failed to load valid map %s (%s)' % (filename, e)) - eq_(len(failures), 0, '\n' + '\n'.join(failures)) + assert len(failures) == 0, '\n' + '\n'.join(failures) mapnik.logger.set_severity(default_logging_severity) @@ -100,8 +80,4 @@ def test_good_files(): failures.append( 'Failed to load valid map %s (%s)' % (filename, e)) - eq_(len(failures), 0, '\n' + '\n'.join(failures)) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert len(failures) == 0, '\n' + '\n'.join(failures) diff --git a/test/python_tests/map_query_test.py b/test/python_tests/map_query_test.py index ab8335e14..268f7fbf3 100644 --- a/test/python_tests/map_query_test.py +++ b/test/python_tests/map_query_test.py @@ -1,63 +1,44 @@ -#!/usr/bin/env python - -import os - -from nose.tools import assert_almost_equal, eq_, raises - import mapnik - -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) +import pytest # map has no layers - - -@raises(IndexError) def test_map_query_throw1(): - m = mapnik.Map(256, 256) - m.zoom_to_box(mapnik.Box2d(-1, -1, 0, 0)) - m.query_point(0, 0, 0) + with pytest.raises(IndexError): + m = mapnik.Map(256, 256) + m.zoom_to_box(mapnik.Box2d(-1, -1, 0, 0)) + m.query_point(0, 0, 0) # only positive indexes - - -@raises(IndexError) def test_map_query_throw2(): - m = mapnik.Map(256, 256) - m.query_point(-1, 0, 0) + with pytest.raises(IndexError): + m = mapnik.Map(256, 256) + m.query_point(-1, 0, 0) # map has never been zoomed (nodata) - - -@raises(RuntimeError) def test_map_query_throw3(): - m = mapnik.Map(256, 256) - m.query_point(0, 0, 0) + with pytest.raises(RuntimeError): + m = mapnik.Map(256, 256) + m.query_point(0, 0, 0) if 'shape' in mapnik.DatasourceCache.plugin_names(): # map has never been zoomed (even with data) - @raises(RuntimeError) def test_map_query_throw4(): - m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml') - m.query_point(0, 0, 0) + with pytest.raises(RuntimeError): + m = mapnik.Map(256, 256) + mapnik.load_map(m, './test/data/good_maps/agg_poly_gamma_map.xml') + m.query_point(0, 0, 0) # invalid coords in general (do not intersect) - @raises(RuntimeError) def test_map_query_throw5(): - m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/agg_poly_gamma_map.xml') - m.zoom_all() - m.query_point(0, 9999999999999999, 9999999999999999) + with pytest.raises(RuntimeError): + m = mapnik.Map(256, 256) + mapnik.load_map(m, './test/data/good_maps/agg_poly_gamma_map.xml') + m.zoom_all() + m.query_point(0, 9999999999999999, 9999999999999999) def test_map_query_works1(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/wgs842merc_reprojection.xml') + mapnik.load_map(m, './test/data/good_maps/wgs842merc_reprojection.xml') merc_bounds = mapnik.Box2d(-20037508.34, - 20037508.34, 20037508.34, 20037508.34) m.maximum_extent = merc_bounds @@ -65,11 +46,11 @@ def test_map_query_works1(): # somewhere in kansas fs = m.query_point(0, -11012435.5376, 4599674.6134) feat = fs.next() - eq_(feat.attributes['NAME_FORMA'], u'United States of America') + assert feat.attributes['NAME_FORMA'] == u'United States of America' def test_map_query_works2(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/merc2wgs84_reprojection.xml') + mapnik.load_map(m, './test/data/good_maps/merc2wgs84_reprojection.xml') wgs84_bounds = mapnik.Box2d(-179.999999975, - 85.0511287776, 179.999999975, 85.0511287776) m.maximum_extent = wgs84_bounds @@ -78,28 +59,28 @@ def test_map_query_works2(): # mapnik.render_to_file(m,'works2.png') # validate that aspect_fix_mode modified the bbox reasonably e = m.envelope() - assert_almost_equal(e.minx, -179.999999975, places=7) - assert_almost_equal(e.miny, -167.951396161, places=7) - assert_almost_equal(e.maxx, 179.999999975, places=7) - assert_almost_equal(e.maxy, 192.048603789, places=7) + assert e.minx == pytest.approx(-179.999999975, abs=1e-7) + assert e.miny == pytest.approx(-167.951396161, abs=1e-7) + assert e.maxx == pytest.approx(179.999999975, abs=1e-7) + assert e.maxy == pytest.approx(192.048603789, abs=1e-7) fs = m.query_point(0, -98.9264, 38.1432) # somewhere in kansas feat = fs.next() - eq_(feat.attributes['NAME'], u'United States') + assert feat.attributes['NAME'] == u'United States' def test_map_query_in_pixels_works1(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/wgs842merc_reprojection.xml') + mapnik.load_map(m, './test/data/good_maps/wgs842merc_reprojection.xml') merc_bounds = mapnik.Box2d(-20037508.34, - 20037508.34, 20037508.34, 20037508.34) m.maximum_extent = merc_bounds m.zoom_all() fs = m.query_map_point(0, 55, 100) # somewhere in middle of us feat = fs.next() - eq_(feat.attributes['NAME_FORMA'], u'United States of America') + assert feat.attributes['NAME_FORMA'] == u'United States of America' def test_map_query_in_pixels_works2(): m = mapnik.Map(256, 256) - mapnik.load_map(m, '../data/good_maps/merc2wgs84_reprojection.xml') + mapnik.load_map(m, './test/data/good_maps/merc2wgs84_reprojection.xml') wgs84_bounds = mapnik.Box2d(-179.999999975, - 85.0511287776, 179.999999975, 85.0511287776) m.maximum_extent = wgs84_bounds @@ -107,14 +88,10 @@ def test_map_query_in_pixels_works2(): m.zoom_all() # validate that aspect_fix_mode modified the bbox reasonably e = m.envelope() - assert_almost_equal(e.minx, -179.999999975, places=7) - assert_almost_equal(e.miny, -167.951396161, places=7) - assert_almost_equal(e.maxx, 179.999999975, places=7) - assert_almost_equal(e.maxy, 192.048603789, places=7) + assert e.minx == pytest.approx(-179.999999975, abs=1e-7) + assert e.miny == pytest.approx(-167.951396161, abs=1e-7) + assert e.maxx == pytest.approx(179.999999975, abs=1e-7) + assert e.maxy == pytest.approx(192.048603789, abs=1e-7) fs = m.query_map_point(0, 55, 100) # somewhere in Canada feat = fs.next() - eq_(feat.attributes['NAME'], u'Canada') - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert feat.attributes['NAME'] == u'Canada' diff --git a/test/python_tests/mapnik_logger_test.py b/test/python_tests/mapnik_logger_test.py index 8c6c5437a..7d7566890 100644 --- a/test/python_tests/mapnik_logger_test.py +++ b/test/python_tests/mapnik_logger_test.py @@ -1,21 +1,12 @@ -#!/usr/bin/env python -from nose.tools import eq_ - import mapnik -from .utilities import run_all - - def test_logger_init(): - eq_(mapnik.severity_type.Debug, 0) - eq_(mapnik.severity_type.Warn, 1) - eq_(mapnik.severity_type.Error, 2) - eq_(getattr(mapnik.severity_type, "None"), 3) + assert mapnik.severity_type.Debug == 0 + assert mapnik.severity_type.Warn == 1 + assert mapnik.severity_type.Error == 2 + assert getattr(mapnik.severity_type, "None") == 3 default = mapnik.logger.get_severity() mapnik.logger.set_severity(mapnik.severity_type.Debug) - eq_(mapnik.logger.get_severity(), mapnik.severity_type.Debug) + assert mapnik.logger.get_severity() == mapnik.severity_type.Debug mapnik.logger.set_severity(default) - eq_(mapnik.logger.get_severity(), default) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert mapnik.logger.get_severity() == default diff --git a/test/python_tests/memory_datasource_test.py b/test/python_tests/memory_datasource_test.py index d19dbb593..fbe1d8987 100644 --- a/test/python_tests/memory_datasource_test.py +++ b/test/python_tests/memory_datasource_test.py @@ -1,21 +1,15 @@ -# encoding: utf8 -from nose.tools import eq_ - import mapnik -from .utilities import run_all - - def test_add_feature(): md = mapnik.MemoryDatasource() - eq_(md.num_features(), 0) + assert md.num_features() == 0 context = mapnik.Context() context.push('foo') feature = mapnik.Feature(context, 1) feature['foo'] = 'bar' feature.geometry = mapnik.Geometry.from_wkt('POINT(2 3)') md.add_feature(feature) - eq_(md.num_features(), 1) + assert md.num_features() == 1 featureset = md.features_at_point(mapnik.Coord(2, 3)) retrieved = [] @@ -23,15 +17,12 @@ def test_add_feature(): for feat in featureset: retrieved.append(feat) - eq_(len(retrieved), 1) + assert len(retrieved) == 1 f = retrieved[0] - eq_(f['foo'], 'bar') + assert f['foo'] == 'bar' featureset = md.features_at_point(mapnik.Coord(20, 30)) retrieved = [] for feat in featureset: retrieved.append(feat) - eq_(len(retrieved), 0) - -if __name__ == "__main__": - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert len(retrieved) == 0 diff --git a/test/python_tests/multi_tile_raster_test.py b/test/python_tests/multi_tile_raster_test.py index 26fd68adc..5ec750dcd 100644 --- a/test/python_tests/multi_tile_raster_test.py +++ b/test/python_tests/multi_tile_raster_test.py @@ -1,26 +1,11 @@ -#!/usr/bin/env python - -import os - -from nose.tools import eq_ - import mapnik -from .utilities import execution_path, run_all - - -def setup(): - # All of the paths used are relative, if we run the tests - # from another directory we need to chdir() - os.chdir(execution_path('.')) - - def test_multi_tile_policy(): srs = 'epsg:4326' lyr = mapnik.Layer('raster') if 'raster' in mapnik.DatasourceCache.plugin_names(): lyr.datasource = mapnik.Raster( - file='../data/raster_tiles/${x}/${y}.tif', + file='./test/data/raster_tiles/${x}/${y}.tif', lox=-180, loy=-90, hix=180, @@ -46,29 +31,25 @@ def test_multi_tile_policy(): mapnik.render(_map, im) # test green chunk - eq_(im.view(0, 64, 1, 1).tostring(), b'\x00\xff\x00\xff') - eq_(im.view(127, 64, 1, 1).tostring(), b'\x00\xff\x00\xff') - eq_(im.view(0, 127, 1, 1).tostring(), b'\x00\xff\x00\xff') - eq_(im.view(127, 127, 1, 1).tostring(), b'\x00\xff\x00\xff') + assert im.view(0, 64, 1, 1).tostring() == b'\x00\xff\x00\xff' + assert im.view(127, 64, 1, 1).tostring() == b'\x00\xff\x00\xff' + assert im.view(0, 127, 1, 1).tostring() == b'\x00\xff\x00\xff' + assert im.view(127, 127, 1, 1).tostring() == b'\x00\xff\x00\xff' # test blue chunk - eq_(im.view(128, 64, 1, 1).tostring(), b'\x00\x00\xff\xff') - eq_(im.view(255, 64, 1, 1).tostring(), b'\x00\x00\xff\xff') - eq_(im.view(128, 127, 1, 1).tostring(), b'\x00\x00\xff\xff') - eq_(im.view(255, 127, 1, 1).tostring(), b'\x00\x00\xff\xff') + assert im.view(128, 64, 1, 1).tostring() == b'\x00\x00\xff\xff' + assert im.view(255, 64, 1, 1).tostring() == b'\x00\x00\xff\xff' + assert im.view(128, 127, 1, 1).tostring() == b'\x00\x00\xff\xff' + assert im.view(255, 127, 1, 1).tostring() == b'\x00\x00\xff\xff' # test red chunk - eq_(im.view(0, 128, 1, 1).tostring(), b'\xff\x00\x00\xff') - eq_(im.view(127, 128, 1, 1).tostring(), b'\xff\x00\x00\xff') - eq_(im.view(0, 191, 1, 1).tostring(), b'\xff\x00\x00\xff') - eq_(im.view(127, 191, 1, 1).tostring(), b'\xff\x00\x00\xff') + assert im.view(0, 128, 1, 1).tostring() == b'\xff\x00\x00\xff' + assert im.view(127, 128, 1, 1).tostring() == b'\xff\x00\x00\xff' + assert im.view(0, 191, 1, 1).tostring() == b'\xff\x00\x00\xff' + assert im.view(127, 191, 1, 1).tostring() == b'\xff\x00\x00\xff' # test magenta chunk - eq_(im.view(128, 128, 1, 1).tostring(), b'\xff\x00\xff\xff') - eq_(im.view(255, 128, 1, 1).tostring(), b'\xff\x00\xff\xff') - eq_(im.view(128, 191, 1, 1).tostring(), b'\xff\x00\xff\xff') - eq_(im.view(255, 191, 1, 1).tostring(), b'\xff\x00\xff\xff') - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert im.view(128, 128, 1, 1).tostring() == b'\xff\x00\xff\xff' + assert im.view(255, 128, 1, 1).tostring() == b'\xff\x00\xff\xff' + assert im.view(128, 191, 1, 1).tostring() == b'\xff\x00\xff\xff' + assert im.view(255, 191, 1, 1).tostring() == b'\xff\x00\xff\xff' diff --git a/test/python_tests/my.pdf b/test/python_tests/my.pdf deleted file mode 100644 index 7d80dfdd8..000000000 Binary files a/test/python_tests/my.pdf and /dev/null differ diff --git a/test/python_tests/topojson_plugin_test.py b/test/python_tests/topojson_plugin_test.py index 5a11a8343..575e9748b 100644 --- a/test/python_tests/topojson_plugin_test.py +++ b/test/python_tests/topojson_plugin_test.py @@ -1,20 +1,20 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -from __future__ import absolute_import, print_function -import os +#from __future__ import absolute_import, print_function -from nose.tools import assert_almost_equal, eq_ +#from nose.tools import assert_almost_equal, eq_ import mapnik +import pytest +#import os -from .utilities import execution_path, run_all +#from .utilities import execution_path, run_all - -def setup(): +#def setup(): # All of the paths used are relative, if we run the tests # from another directory we need to chdir() - os.chdir(execution_path('.')) +# os.chdir(execution_path('.')) if 'topojson' in mapnik.DatasourceCache.plugin_names(): @@ -23,91 +23,75 @@ def test_topojson_init(): # topojson version 1.4.2 ds = mapnik.Datasource( type='topojson', - file='../data/topojson/escaped.topojson') + file='./test/data/topojson/escaped.topojson') e = ds.envelope() - assert_almost_equal(e.minx, -81.705583, places=7) - assert_almost_equal(e.miny, 41.480573, places=6) - assert_almost_equal(e.maxx, -81.705583, places=5) - assert_almost_equal(e.maxy, 41.480573, places=3) + assert e.minx == pytest.approx(-81.705583, 1e-7) + assert e.miny == pytest.approx( 41.480573, 1e-6) + assert e.maxx == pytest.approx(-81.705583, 1e-5) + assert e.maxy == pytest.approx(41.480573, 1e-3) def test_topojson_properties(): - ds = mapnik.Datasource( - type='topojson', - file='../data/topojson/escaped.topojson') - f = list(ds.features_at_point(ds.envelope().center()))[0] - eq_(len(ds.fields()), 11) - desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') - - ds = mapnik.Datasource( - type='topojson', - file='../data/topojson/escaped.topojson') - f = list(ds.all_features())[0] - eq_(len(ds.fields()), 11) - - desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') + ds = mapnik.Datasource( + type='topojson', + file='./test/data/topojson/escaped.topojson') + + f = list(ds.features_at_point(ds.envelope().center()))[0] + assert len(ds.fields()) == 11 + desc = ds.describe() + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' def test_geojson_from_in_memory_string(): ds = mapnik.Datasource( type='topojson', inline=open( - '../data/topojson/escaped.topojson', + './test/data/topojson/escaped.topojson', 'r').read()) - f = list(ds.all_features())[0] - eq_(len(ds.fields()), 11) - + f = list(ds.features_at_point(ds.envelope().center()))[0] + assert len(ds.fields()) == 11 desc = ds.describe() - eq_(desc['geometry_type'], mapnik.DataGeometryType.Point) - - eq_(f['name'], u'Test') - eq_(f['int'], 1) - eq_(f['description'], u'Test: \u005C') - eq_(f['spaces'], u'this has spaces') - eq_(f['double'], 1.1) - eq_(f['boolean'], True) - eq_(f['NOM_FR'], u'Qu\xe9bec') - eq_(f['NOM_FR'], u'Québec') - -# @raises(RuntimeError) + assert desc['geometry_type'] == mapnik.DataGeometryType.Point + + assert f['name'] == u'Test' + assert f['int'] == 1 + assert f['description'] == u'Test: \u005C' + assert f['spaces'] == u'this has spaces' + assert f['double'] == 1.1 + assert f['boolean'] == True + assert f['NOM_FR'] == u'Qu\xe9bec' + assert f['NOM_FR'] == u'Québec' + + #@raises(RuntimeError) def test_that_nonexistant_query_field_throws(**kwargs): + #with pytest.raises(RuntimeError): ds = mapnik.Datasource( type='topojson', - file='../data/topojson/escaped.topojson') - eq_(len(ds.fields()), 11) + file='./test/data/topojson/escaped.topojson') + assert len(ds.fields()) == 11 # TODO - this sorting is messed up - eq_(ds.fields(), ['name', 'int', 'description', - 'spaces', 'double', 'boolean', 'NOM_FR', - 'object', 'array', 'empty_array', 'empty_object']) - eq_(ds.field_types(), ['str', 'int', - 'str', 'str', 'float', 'bool', 'str', - 'str', 'str', 'str', 'str']) -# TODO - should topojson plugin throw like others? -# query = mapnik.Query(ds.envelope()) -# for fld in ds.fields(): -# query.add_property_name(fld) -# # also add an invalid one, triggering throw -# query.add_property_name('bogus') -# fs = ds.features(query) - -if __name__ == "__main__": - setup() - exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) + assert ds.fields() == ['name', 'int', 'description', + 'spaces', 'double', 'boolean', 'NOM_FR', + 'object', 'array', 'empty_array', 'empty_object'] + assert ds.field_types() == ['str', 'int', + 'str', 'str', 'float', 'bool', 'str', + 'str', 'str', 'str', 'str'] + # TODO - should topojson plugin throw like others? + query = mapnik.Query(ds.envelope()) + for fld in ds.fields(): + query.add_property_name(fld) + # also add an invalid one, triggering throw + query.add_property_name('bogus') + fs = ds.features(query) + + +#if __name__ == "__main__": + #setup() +# exit(run_all(eval(x) for x in dir() if x.startswith("test_"))) diff --git a/test/python_tests/utilities.py b/test/python_tests/utilities.py index 9bfc9aec6..8500d5350 100644 --- a/test/python_tests/utilities.py +++ b/test/python_tests/utilities.py @@ -4,10 +4,6 @@ import os import sys import traceback - -from nose.plugins.errorclass import ErrorClass, ErrorClassPlugin -from nose.tools import assert_almost_equal - import mapnik PYTHON3 = sys.version_info[0] == 3 @@ -22,17 +18,6 @@ def execution_path(filename): return os.path.join(os.path.dirname( sys._getframe(1).f_code.co_filename), filename) - -class Todo(Exception): - pass - - -class TodoPlugin(ErrorClassPlugin): - name = "todo" - - todo = ErrorClass(Todo, label='TODO', isfailure=False) - - def contains_word(word, bytestring_): """ Checks that a bytestring contains a given word. len(bytestring) should be diff --git a/vcpkg.json b/vcpkg.json new file mode 100644 index 000000000..b0cb1f643 --- /dev/null +++ b/vcpkg.json @@ -0,0 +1,12 @@ +{ + "name": "python-mapnik", + "dependencies": [ + { + "name": "boost-python", + "features": [ + "python3" + ] + }, + "mapnik" + ] +}