Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

18.2 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project

import test from 'tape-catch';
import {KeplerGlLayers} from '@kepler.gl/layers';
import {testCreateCases} from 'test/helpers/layer-utils';

const {WMSLayer} = KeplerGlLayers;

// Shared test fixtures
const MOCK_WMS_LAYER_CONFIG = {
  name: 'test_layer',
  title: 'Test WMS Layer',
  boundingBox: [
    [-180, -90],
    [180, 90]
  ],
  queryable: true
};

const MOCK_WMS_DATASET = {
  type: 'wms-tile',
  metadata: {
    tilesetDataUrl: 'http://example.com/wms',
    label: 'Test WMS Dataset',
    layers: [MOCK_WMS_LAYER_CONFIG]
  }
};

const MOCK_RENDER_OPTS = {
  data: {
    tilesetDataUrl: 'http://example.com/wms',
    metadata: {layers: [MOCK_WMS_LAYER_CONFIG]}
  },
  mapState: {dragRotate: false},
  interactionConfig: {tooltip: {enabled: true}},
  layerCallbacks: {onWMSFeatureInfo: () => {}}
};

// Mock DOMParser for browser environment
global.DOMParser = class MockDOMParser {
  parseFromString(str) {
    const createMockElement = (tagName, textContent = '') => ({
      tagName,
      textContent,
      children: [],
      getElementsByTagName: name =>
        Array.from(this.children).filter(child => child.tagName === name)
    });

    // Simple mock for the specific XML structure used in tests
    if (str.includes('conus:RED_BAND')) {
      return {
        getElementsByTagName: name => {
          if (name === 'gml:featureMember') {
            return [
              {
                children: [
                  {
                    children: [
                      createMockElement('conus:RED_BAND', '255.0'),
                      createMockElement('conus:GREEN_BAND', '195.0'),
                      createMockElement('conus:BLUE_BAND', '0.0'),
                      createMockElement('conus:ALPHA_BAND', '255.0')
                    ]
                  }
                ]
              }
            ];
          }
          return [];
        }
      };
    }

    return {getElementsByTagName: () => []};
  }
};

// Helper function to create a configured WMS layer
function createWMSLayer(config = {}) {
  const layer = new WMSLayer({
    id: 'test-wms-layer',
    dataId: 'wms-dataset',
    ...config
  });

  layer.updateLayerVisConfig({
    wmsLayer: MOCK_WMS_LAYER_CONFIG,
    opacity: 0.8,
    transparent: true,
    ...config.visConfig
  });

  return layer;
}

test('#WMSLayer -> constructor', t => {
  const TEST_CASES = {
    CREATE: [
      {
        props: {
          dataId: 'wms-test-data',
          isVisible: true,
          label: 'test wms layer'
        },
        test: layer => {
          t.ok(layer.config.dataId === 'wms-test-data', 'WMSLayer dataId should be correct');
          t.ok(layer.type === 'wms', 'type should be wms');
          t.ok(layer.isAggregated === false, 'WMSLayer is not aggregated');
          t.ok(layer.config.label === 'test wms layer', 'label should be correct');
          t.ok(layer.config.isVisible === true, 'should be visible by default');
          t.ok(layer.config.visConfig, 'should have visConfig');
          t.equal(layer.config.visConfig.opacity, 0.8, 'should have default opacity');
          t.equal(layer.config.visConfig.transparent, true, 'should be transparent by default');
          t.equal(layer.config.visConfig.allowHover, false, 'should disable hover by default');
          t.equal(layer.config.visConfig.wmsLayer, null, 'should have null wmsLayer initially');
          t.ok(typeof layer.layerIcon === 'function', 'should have layerIcon');
          t.deepEqual(
            layer.supportedDatasetTypes,
            ['wms-tile'],
            'should support wms-tile dataset type'
          );
        }
      }
    ]
  };

  testCreateCases(t, WMSLayer, TEST_CASES.CREATE);
  t.end();
});

test('#WMSLayer -> legend visual channels', t => {
  const layer = createWMSLayer();

  t.deepEqual(
    layer.getLegendVisualChannels(),
    {},
    'should expose no legend channels (WMS has no fill color)'
  );

  t.end();
});

test('#WMSLayer -> getLegendImageUrl', t => {
  const layer = createWMSLayer({
    visConfig: {
      wmsLayer: {
        ...MOCK_WMS_LAYER_CONFIG,
        legendUrl: 'https://example.com/legend.png'
      }
    }
  });

  t.equal(
    layer.getLegendImageUrl(),
    'https://example.com/legend.png',
    'should use LegendURL stored on the selected WMS layer'
  );

  const layerWithoutLegend = createWMSLayer();
  t.equal(
    layerWithoutLegend.getLegendImageUrl(),
    null,
    'should return null before dataset meta has a service URL'
  );

  layerWithoutLegend.updateLayerMeta(MOCK_WMS_DATASET);
  const constructed = layerWithoutLegend.getLegendImageUrl();
  t.ok(constructed, 'should construct GetLegendGraphic from dataset URL');
  t.ok(
    constructed.includes('GetLegendGraphic'),
    'constructed legend URL should request GetLegendGraphic'
  );
  t.ok(constructed.includes('test_layer'), 'constructed legend URL should include layer name');

  const restoredLayer = createWMSLayer({
    visConfig: {
      wmsLayer: {
        ...MOCK_WMS_LAYER_CONFIG,
        legendUrl: 'https://stale.example/old-legend.png'
      }
    }
  });
  restoredLayer.updateLayerMeta({
    type: 'wms-tile',
    metadata: {
      tilesetDataUrl: 'http://example.com/wms',
      version: '1.3.0',
      layers: [
        {
          ...MOCK_WMS_LAYER_CONFIG,
          legendUrl: 'https://example.com/refreshed-legend.png'
        }
      ]
    }
  });
  t.equal(
    restoredLayer.getLegendImageUrl(),
    'https://example.com/refreshed-legend.png',
    'should use advertised LegendURL from refreshed dataset metadata'
  );
  t.equal(
    restoredLayer.config.visConfig.wmsLayer.legendUrl,
    'https://example.com/refreshed-legend.png',
    'should reconcile selected wmsLayer with refreshed metadata'
  );

  t.end();
});

test('WMSLayer -> basic layer functionality', t => {
  const layer = createWMSLayer();

  // Test layer configuration
  t.deepEqual(
    layer.config.visConfig.wmsLayer,
    MOCK_WMS_LAYER_CONFIG,
    'should update wmsLayer config'
  );
  t.equal(layer.config.visConfig.opacity, 0.8, 'should have correct opacity');
  t.equal(layer.config.visConfig.transparent, true, 'should be transparent');

  // Test layer properties
  t.equal(layer.name, 'WMS Tile', 'should have correct layer name');
  t.ok(layer.layerIcon, 'should have layer icon');
  t.equal(layer.requireData, true, 'WMS layer should require data');
  t.ok(layer.isValidToSave(), 'should be valid to save');

  // Test _getCurrentServiceLayer
  const serviceLayer = layer._getCurrentServiceLayer();
  t.ok(serviceLayer, 'should return service layer when configured');
  t.equal(serviceLayer.name, 'test_layer', 'should return correct service layer');

  t.end();
});

test('WMSLayer -> hover functionality', t => {
  const mockObjectInfo = {
    picked: true,
    layer: {props: {id: 'test-wms-layer'}}
  };

  const disabledLayer = createWMSLayer();
  t.equal(disabledLayer.config.visConfig.allowHover, false, 'hover is disabled by default');
  t.equal(
    disabledLayer.hasHoveredObject(mockObjectInfo),
    null,
    'should not hover when allowHover is off'
  );
  t.equal(
    disabledLayer.getHoverData(null, null, [], null, {index: 0, x: 100, y: 200}),
    null,
    'should not return hover data when allowHover is off'
  );

  const layer = createWMSLayer({visConfig: {allowHover: true}});

  const hoveredObject = layer.hasHoveredObject(mockObjectInfo);
  t.ok(hoveredObject, 'should return hovered object when layer is picked');
  t.equal(hoveredObject.index, 0, 'should return index 0 for WMS layer');

  // Test hasHoveredObject with no picked object
  const hoveredObjectNotPicked = layer.hasHoveredObject({...mockObjectInfo, picked: false});
  t.equal(hoveredObjectNotPicked, null, 'should return null when layer is not picked');

  // Test getHoverData with hover coordinates
  const hoverData = layer.getHoverData(null, null, [], null, {index: 0, x: 100, y: 200});
  t.ok(hoverData, 'should return hover data for WMS layer');
  t.ok(hoverData.fieldValues, 'should have fieldValues array');
  t.equal(hoverData.fieldValues.length, 1, 'should have 1 field value');
  t.equal(hoverData.fieldValues[0].labelMessage, 'layer.wms.hover', 'should have WMS hover label');

  // Test getHoverData with WMS feature info - string format
  const wmsFeatureInfoObject = {
    wmsFeatureInfo: '<FeatureInfo><Feature>Test feature data</Feature></FeatureInfo>'
  };
  const wmsHoverData = layer.getHoverData(wmsFeatureInfoObject, null, [], null, {index: 0});
  t.ok(wmsHoverData.wmsFeatureData, 'should have wmsFeatureData array');
  t.equal(wmsHoverData.wmsFeatureData.length, 1, 'should have 1 feature data item');

  // Test getHoverData with WMS feature info - array format
  const wmsFeatureInfoArrayObject = {
    wmsFeatureInfo: [
      {name: 'RED BAND', value: '255.0'},
      {name: 'GREEN BAND', value: '195.0'},
      {name: 'BLUE BAND', value: '0.0'}
    ]
  };
  const wmsArrayHoverData = layer.getHoverData(wmsFeatureInfoArrayObject, null, [], null, {
    index: 0
  });
  t.equal(wmsArrayHoverData.wmsFeatureData.length, 3, 'should have 3 feature data items');
  t.equal(
    wmsArrayHoverData.wmsFeatureData[0].name,
    'RED BAND',
    'should have correct attribute name'
  );

  t.end();
});

test('#WMSLayer -> renderLayer variations', t => {
  const baseLayer = createWMSLayer();

  // Test normal rendering
  const deckLayers = baseLayer.renderLayer(MOCK_RENDER_OPTS);
  t.ok(deckLayers, 'should create deck layers');
  t.equal(deckLayers.length, 1, 'should render one deck layer');

  const deckLayer = deckLayers[0];
  t.equal(deckLayer.id, 'test-wms-layer-WMSLayer', 'should have correct layer id');
  t.equal(deckLayer.props.pickable, false, 'should not be pickable when hover is disabled');
  t.equal(deckLayer.props.onClick, null, 'should not query feature info when hover is disabled');
  t.equal(deckLayer.props.serviceType, 'wms', 'should have correct service type');
  t.deepEqual(deckLayer.props.layers, ['test_layer'], 'should have correct layers');
  t.equal(deckLayer.props.opacity, 0.8, 'should have correct opacity');

  const hoverLayer = createWMSLayer({visConfig: {allowHover: true}});
  const hoverDeckLayers = hoverLayer.renderLayer(MOCK_RENDER_OPTS);
  t.equal(
    hoverDeckLayers[0].props.pickable,
    true,
    'should be pickable when allowHover, tooltips, and queryable are enabled'
  );
  t.ok(typeof hoverDeckLayers[0].props.onClick === 'function', 'should have onClick handler');

  // Test with tooltips disabled
  const tooltipsDisabledOpts = {
    ...MOCK_RENDER_OPTS,
    interactionConfig: {tooltip: {enabled: false}}
  };
  const nonPickableLayers = hoverLayer.renderLayer(tooltipsDisabledOpts);
  t.equal(
    nonPickableLayers[0].props.pickable,
    false,
    'should not be pickable when tooltips disabled'
  );

  // Test with non-queryable layer
  const nonQueryableLayer = createWMSLayer({
    visConfig: {allowHover: true, wmsLayer: {...MOCK_WMS_LAYER_CONFIG, queryable: false}}
  });
  const nonQueryableLayers = nonQueryableLayer.renderLayer(MOCK_RENDER_OPTS);
  t.equal(
    nonQueryableLayers[0].props.pickable,
    false,
    'should not be pickable when layer is not queryable'
  );

  // Test without wmsLayer config
  const unconfiguredLayer = new WMSLayer({id: 'test-wms-layer', dataId: 'wms-dataset'});
  const emptyLayers = unconfiguredLayer.renderLayer(MOCK_RENDER_OPTS);
  t.equal(emptyLayers.length, 0, 'should not render any layers without wmsLayer config');

  t.end();
});

test('#WMSLayer -> formatLayerData', t => {
  const layer = createWMSLayer();

  const mockDatasets = {'wms-dataset': MOCK_WMS_DATASET};
  const layerData = layer.formatLayerData(mockDatasets);
  t.ok(layerData, 'should return layer data object');
  t.equal(layerData.tilesetDataUrl, 'http://example.com/wms', 'should have tileset data URL');
  t.ok(layerData.metadata, 'should have metadata');

  t.end();
});

test('#WMSLayer -> updateLayerMeta', t => {
  const layer = createWMSLayer();

  // Test with non-WMS dataset
  t.doesNotThrow(() => {
    layer.updateLayerMeta({type: 'csv'});
  }, 'should not throw with non-WMS dataset');

  // Test with WMS dataset
  t.doesNotThrow(() => {
    layer.updateLayerMeta({type: 'wms-tile'});
  }, 'should update meta with WMS dataset');

  t.deepEqual(
    layer.meta.bounds,
    [
      [-180, -90],
      [180, 90]
    ],
    'should set bounds from bounding box'
  );

  t.end();
});

test('#WMSLayer -> parseWMSFeatureInfo', t => {
  const layer = createWMSLayer();

  const xmlString = `<?xml version="1.0" encoding="UTF-8"?>
<wfs:FeatureCollection xmlns="http://www.opengis.net/wfs" xmlns:wfs="http://www.opengis.net/wfs" xmlns:gml="http://www.opengis.net/gml" xmlns:conus="http://conus" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.opengis.net/wfs https://opengeo.ncep.noaa.gov/geoserver/schemas/wfs/1.0.0/WFS-basic.xsd">
  <gml:featureMember>
    <conus:conus_cref_qcd fid="">
      <conus:RED_BAND>255.0</conus:RED_BAND>
      <conus:GREEN_BAND>195.0</conus:GREEN_BAND>
      <conus:BLUE_BAND>0.0</conus:BLUE_BAND>
      <conus:ALPHA_BAND>255.0</conus:ALPHA_BAND>
    </conus:conus_cref_qcd>
  </gml:featureMember>
</wfs:FeatureCollection>`;

  const parsedAttributes = layer.parseWMSFeatureInfo(xmlString);
  t.ok(Array.isArray(parsedAttributes), 'should return an array');
  t.equal(parsedAttributes.length, 4, 'should parse 4 attributes');
  t.equal(parsedAttributes[0].name, 'RED BAND', 'should parse RED_BAND attribute name correctly');
  t.equal(parsedAttributes[0].value, '255.0', 'should parse RED_BAND attribute value correctly');
  t.equal(
    parsedAttributes[1].name,
    'GREEN BAND',
    'should parse GREEN_BAND attribute name correctly'
  );
  t.equal(parsedAttributes[1].value, '195.0', 'should parse GREEN_BAND attribute value correctly');

  // Test edge cases
  t.deepEqual(layer.parseWMSFeatureInfo(''), [], 'should return empty array for empty XML');
  t.deepEqual(
    layer.parseWMSFeatureInfo('<invalid>xml</invalid>'),
    [],
    'should return empty array for invalid XML'
  );

  t.end();
});

test('#WMSLayer -> findDefaultLayerProps', t => {
  // Test with valid WMS dataset
  const result = WMSLayer.findDefaultLayerProps(MOCK_WMS_DATASET);
  t.ok(result.props, 'should return props object');
  t.equal(result.props.length, 1, 'should return one layer prop for WMS dataset');
  t.equal(result.props[0].label, 'Test WMS Dataset', 'should use dataset label');
  t.deepEqual(
    result.props[0].layers,
    MOCK_WMS_DATASET.metadata.layers,
    'should pass through all layers'
  );

  // Test with non-WMS dataset
  const nonWmsResult = WMSLayer.findDefaultLayerProps({
    type: 'csv',
    metadata: {label: 'CSV Dataset'}
  });
  t.deepEqual(nonWmsResult.props, [], 'should return empty props for non-WMS dataset');

  // Test with empty WMS dataset
  const emptyWmsDataset = {type: 'wms-tile', metadata: {label: 'Empty WMS Dataset', layers: []}};
  const emptyResult = WMSLayer.findDefaultLayerProps(emptyWmsDataset);
  t.equal(
    emptyResult.props.length,
    1,
    'should return one prop even for WMS dataset with no layers'
  );
  t.deepEqual(emptyResult.props[0].layers, [], 'should have empty layers array');

  t.end();
});

test('#WMSLayer -> edge cases and error handling', t => {
  const layer = createWMSLayer();

  // Test formatLayerData with missing dataset
  t.doesNotThrow(() => {
    const emptyLayerData = layer.formatLayerData({}, {}, {});
    t.ok(emptyLayerData, 'should return layer data object even with missing dataset');
    t.equal(emptyLayerData.tilesetDataUrl, null, 'should handle missing dataset gracefully');
  }, 'should not throw error when formatting with missing dataset');

  // Test layer visibility
  const invisibleLayer = createWMSLayer({isVisible: false, visConfig: {allowHover: true}});
  t.equal(invisibleLayer.config.isVisible, false, 'should respect initial visibility setting');

  // Test hasHoveredObject when layer is not visible
  const mockObjectInfo = {picked: true, layer: {props: {id: 'test-wms-layer'}}};
  const hoveredObject = invisibleLayer.hasHoveredObject(mockObjectInfo);
  t.ok(hoveredObject, 'should return hovered object even when layer is not visible');

  // Test getWMSFeatureInfo with no picked deck layer
  layer['getWMSFeatureInfo'](100, 200)
    .then(result => {
      t.equal(result, null, 'should return null when no picked deck layer');
    })
    .catch(_error => {
      t.fail('should not throw error when no picked deck layer');
    });

  t.end();
});

test('#WMSLayer -> split-map clicks query the picked panel image', async t => {
  const layer = createWMSLayer({visConfig: {allowHover: true}});
  const calls = [];
  const results = [];
  const opts = {
    ...MOCK_RENDER_OPTS,
    visible: true,
    layerCallbacks: {onWMSFeatureInfo: result => results.push(result)}
  };
  const [left] = layer.renderLayer(opts);
  const [right] = layer.renderLayer({...opts, mapState: {longitude: 60, zoom: 5}});
  const configurePanel = (deckLayer, bbox, width, response) => {
    deckLayer.state = {
      lastRequestParameters: {bbox, width, height: 100, layers: ['test_layer']},
      imageSource: {
        getFeatureInfoText: async params => {
          calls.push(params);
          return response;
        }
      }
    };
  };
  configurePanel(left, [-10, -5, 10, 5], 200, 'left');
  configurePanel(right, [55, 20, 65, 30], 400, 'right');
  layer.parseWMSFeatureInfo = value => [{name: 'PANEL', value}];
  const coordinate = [0, 0];
  const clickResult = left.props.onClick({
    layer: left,
    bitmap: {pixel: [17, 23]},
    coordinate
  });
  t.equal(clickResult, undefined, 'click propagates to the normal selection handler');
  await new Promise(resolve => setTimeout(resolve, 0));
  t.deepEqual(calls[0].bbox, [-10, -5, 10, 5], 'uses the left image bounds');
  t.equal(calls[0].width, 200, 'uses the left image resolution');
  t.deepEqual([calls[0].x, calls[0].y], [17, 23], 'uses pixels picked from that image');
  t.deepEqual(results[0].featureInfo, [{name: 'PANEL', value: 'left'}]);
  t.equal(results[0].coordinate, coordinate, 'preserves the selection coordinate identity');

  const [hiddenRight] = layer.renderLayer({...opts, visible: false});
  configurePanel(hiddenRight, [100, 20, 110, 30], 600, 'hidden');
  await layer._onClick(opts.layerCallbacks, {
    layer: left,
    bitmap: {pixel: [4, 5]},
    coordinate: [1, 1]
  });
  t.deepEqual(calls[1].bbox, [-10, -5, 10, 5], 'a hidden panel render cannot replace the source');
  t.end();
});