#!/bin/bash
set -e

DEB_HOST_ARCH=$(dpkg-architecture -qDEB_HOST_ARCH)

# Do not require an installation of pytest-pyvista, since we do not have a cache
# to test against anyways
cat <<EOF >> tests/plotting/conftest.py
@pytest.fixture()
def verify_image_cache(request, pytestconfig):
    return lambda plotter: True
EOF

# Disable some tests which are failing
declare -a DISABLED_TESTS
DISABLED_TESTS=(
    ### TESTS/CORE ###
    # tests/core/test_dataset.py::test_partition
    # requires vtkRedistributeDataSetFilter, which is not available in debian's vtk
    "test_partition"

    # tests/core/test_dataset.py::test_multiprocessing [xml or legacy]
    # tests/core/test_dataset_filters.py::test_compute_derivatives
    # tests/core/test_dataobject_filters.py::test_slice_along_line_composite
    # tests/core/test_polydata.py::test_clean
    # tests/core/test_polydata.py::test_merge_main_has_priority_deprecated
    # flakey test, often segfaults
    "test_multiprocessing"
    "test_compute_derivatives"
    "test_slice_along_line_composite"
    "test_clean"
    "test_merge_main_has_priority_deprecated"

    # tests/core/test_dataset_filters.py::test_sample_over_line
    # tests/core/test_dataset_filters.py::test_sample_over_multiple_lines
    # tests/core/test_polydata.py::test_point_normals_computes_new_normals
    # need to relax the np.allclose tolerance to pass
    "test_sample_over_line"
    "test_sample_over_multiple_lines"
    "test_point_normals_computes_new_normals"

    # tests/core/test_dataset_filters.py::test_color_labels_color_type_cmap
    # fails with numpy array shape mismatch
    "test_color_labels_color_type_cmap"

    # tests/core/test_polydata.py::test_n_faces
    # does not raise an attribute error
    "test_n_faces"

    # tests/core/test_datasetattributes.py::test_preserve_field_data_after_extract_cells
    # failed at least once on amd64 with
    # "Unreliable test timings! On an initial run, this test took 309.45ms, which exceeded the deadline
    # of 200.00ms, but on a subsequent run it took 3.58 ms, which did not"
    "test_preserve_field_data_after_extract_cells"

    # tests/core/test_datasetattributes.py::test_complex_raises
    # fails on 32 bit archs armel and i386 due to np.complex256 not being available
    "test_complex_raises"

    # tests/core/test_helpers.py::test_wrap_pyvista_ndarray_vtk
    # RuntimeWarning: invalid value encountered in cast
    "test_wrap_pyvista_ndarray_vtk"

    # tests/core/test_imaging.py::test_sample_function[uint64]
    # tests/core/test_imaging.py::test_sample_function[int64]
    # fails on 32 bit archs armel and i386 due to 64-bit integers not being available
    "test_sample_function[uint64]"
    "test_sample_function[int64]"

    # tests/core/test_imagedata_filters.py::test_contour_labeled
    # tests/core/test_imagedata_filters.py::test_contour_labeled_with_smoothing
    # tests/core/test_imagedata_filters.py::test_contour_labeled_with_boundary_output_style
    # asserts randomly fail due to maximum values different from the expected ones
    "test_contour_labeled"
    "test_contour_labeled_with_smoothing"
    "test_contour_labeled_with_boundary_output_style"

    # tests/core/test_reader.py::test_nrrd_reader
    # fails with debian's vtk with error message
    # "No whole extent has been set in the information for output port 0 on algorithm vtkPNrrdReader"
    "test_nrrd_reader"
    "test_pad_image_raises"
    "test_points_to_cells_and_cells_to_points_dimensions"
    "test_pad_image_multi_component_with_scalar"

    # tests/core/test_reader.py::test_hdf_reader
    # fails on arm64, armel, ppc64el, s390x with
    # Unknown native datatype: 216172782113784226', 'vtkHDFReaderImplementation.cxx'
    "test_hdf_reader"

    # tests/core/test_reader.py::test_xdmf_reader
    # requires vtkmodules.vtkIOXdmf2, which seems not be available with debian's vtk
    "test_xdmf_reader"

    # tests/core/test_reader.py::test_openfoamreader_read_data_time_point
    # tests/core/test_reader.py::test_openfoamreader_read_data_time_value
    # need to relax the np.iclose tolerance to pass on i386
    "test_openfoamreader_read_data_time_point"
    "test_openfoamreader_read_data_time_value"

    # tests/core/test_utilities.py::test_lines_segments_from_points
    # exceeds timeout on riscv64
    "test_lines_segments_from_points"

    # tests/core/test_datasetattributes.py and
    # tests/core/test_geometric_objects.py
    # hypothesis input generation is too slow and gives error
    "test_set_array_string_lists_should_equal"
    "test_set_array_string_array_should_equal"
    "test_box_source_bounds_raise"
    "test_pyramid_raises"
    "test_quadrilateral_raises"

    ### TESTS/PLOTTING ###

    # tests/plotting/test_plotting.py::test_set_environment_texture_cubemap
    # seems to hang
    "test_set_environment_texture_cubemap"

    # tests/plotting/test_plotting.py::test_ssaa_pass
    # does not raise a runtime error
    "test_ssao_pass"

    # tests/plotting/test_theme.py::test_load_theme
    # tests/plotting/test_theme.py::test_save_before_close_callback
    # each one of these tests requires trame
    "test_load_theme"
    "test_save_before_close_callback"

    # tests/plotting/test_theme.py::test_anti_aliasing_fxaa
    # fails garbage collection
    "test_anti_aliasing_fxaa"

    # tests/plotting/test_plotting.py::test_plot_nan_color
    # tests/plotting/test_render_window_interactor.py::test_timer
    # randomly gives segmentation faults
    "test_plot_nan_color"
    "test_timer"

    # tests/plotting/test_renderer.py::test_show_bounds_padding_raises
    # exceeds timeout on ppc64el
    "test_show_bounds_padding_raises"

    # tests/plotting/test_renderer.py
    # hypothesis input generation is too slow and gives error
    "test_init_renderers_groups_item_len_raises"

    ### TESTS/NAMESPACE ###

    # tests/namespace/test_utilities_namespace.py::test_utilities_namespace
    # does not emit the required warning
    "test_utilities_namespace"

    ### TESTS/TYPING ###
    # tests/typing/mypy_plugin/test_plugin.py::test_promote_type_static
    # requires mypy
    "test_promote_type_static"
)

# test needing network access are tested separately in run-unit-tests-network
NETWORK_TESTS=(
 test_download
 test_download_files
 test_dataset_loader
 test_examples
 test_meshio
 test_protein_ribbon   # core/test_polydata_filters.py
 test_reader
 test_composite
 test_user_logo
 test_actor_texture
 test_import_3ds
 test_remove_environment_texture_cubemap
 test_import_obj_with_texture
 test_import_obj
 test_voxelize_volume
 test_property_pbr
 test_get_background_texture
 test_brush
 test_logo_widget
)
DISABLED_TESTS=("${DISABLED_TESTS[@]}" "${NETWORK_TESTS[@]}")

if [ "${DEB_HOST_ARCH}" = "i386" ] ; then
    DISABLED_TESTS=("${DISABLED_TESTS[@]}"
	# fails GC
	test_plot_logo

	# fails numerical check (isclose)
	test_rotate_should_match_vtk_rotation
	test_principal_axes
	test_transform_with_point
	test_translate_direction_collinear
	test_connectivity_closest_point
	test_connectivity_largest
	test_connectivity_cell_seed
	test_connectivity_specified
	test_connectivity_all
	test_connectivity_point_seed
	test_compute_boundary_mesh_quality
	test_streamlines_max_length

	# fails regex pattern
	test_validate_dim_operation_invalid_parameters
    )
fi

if [ "${DEB_HOST_ARCH}" = "riscv64" ] ; then
    # times out
    DISABLED_TESTS=("${DISABLED_TESTS[@]}"
    test_axis_scale
    )
fi

if [ "${DEB_HOST_ARCH}" = "s390x" ] ; then
    DISABLED_TESTS=("${DISABLED_TESTS[@]}"
	# fails GC
	test_import_gltf test_remove_vertices_actor
	# times out
	test_volume_rendering_rectilinear
	# fails VTKHDF I/O
	test_save
	test_user_dict_write_read
	)
fi

DISABLED_TESTS_SEPARATOR=" or "
DISABLED_TESTS_STRING=$(printf "${DISABLED_TESTS_SEPARATOR}%s" "${DISABLED_TESTS[@]}")
DISABLED_TESTS_STRING=${DISABLED_TESTS_STRING:${#DISABLED_TESTS_SEPARATOR}}

# Print report about pyvista installation
python3 -c "import pyvista; print(pyvista.Report())"

# Run the remaining tests through xvfb-run, since plotting tests require a
# virtual frame buffer
xvfb-run -a python3 -P -m pytest \
    -k "not (${DISABLED_TESTS_STRING})" \
    -vv --random-order \
    tests
