Ejemplo n.º 1
0
def test_sample_hook(builtins, tmp_plugin: DynamicPlugin):

    viewer = ViewerModel()
    NAME = tmp_plugin.name
    KEY = 'random data'
    with pytest.raises(KeyError, match=f"Plugin {NAME!r} does not provide"):
        viewer.open_sample(NAME, KEY)

    @tmp_plugin.contribute.sample_data(key=KEY)
    def _generate_random_data(shape=(512, 512)):
        data = np.random.rand(*shape)
        return [(data, {'name': KEY})]

    LOGO = str(Path(napari.__file__).parent / 'resources' / 'logo.png')
    tmp_plugin.manifest.contributions.sample_data.append(
        SampleDataURI(uri=LOGO, key='napari logo', display_name='Napari logo')
    )

    assert len(viewer.layers) == 0
    viewer.open_sample(NAME, KEY)
    assert viewer.layers[-1].source == Source(
        path=None, reader_plugin=None, sample=(NAME, KEY)
    )
    assert len(viewer.layers) == 1
    viewer.open_sample(NAME, 'napari logo')
    assert viewer.layers[-1].source == Source(
        path=LOGO, reader_plugin='napari', sample=(NAME, 'napari logo')
    )

    # test calling with kwargs
    viewer.open_sample(NAME, KEY, shape=(256, 256))
    assert len(viewer.layers) == 3
    assert viewer.layers[-1].source == Source(sample=(NAME, KEY))
Ejemplo n.º 2
0
def test_add_layers_with_plugins(layer_datum):
    """Test that add_layers_with_plugins adds the expected layer types."""
    with patch(
        "napari.plugins.io.read_data_with_plugins",
        MagicMock(return_value=([layer_datum], _testimpl)),
    ):
        v = ViewerModel()
        v._add_layers_with_plugins('mock_path')
        layertypes = [layer._type_string for layer in v.layers]
        assert layertypes == [layer_datum[2]]

        expected_source = Source(path='mock_path', reader_plugin='testimpl')
        assert all(lay.source == expected_source for lay in v.layers)
Ejemplo n.º 3
0
    def test_get_channel_data_from_layer_source(self, mock_aics_image):
        # Arrange
        data = numpy.ones((75, 100, 100))
        mock_image = create_autospec(AICSImage)
        mock_aics_image.return_value = mock_image
        img_path = "/path/to/image.tiff"
        layer = MockLayer(name="Test", source=Source(path=img_path, reader_plugin="builtins"))
        mock_image.get_image_data.return_value = data

        # Act
        result = self._layer_reader.get_channel_data(1, layer)

        # Assert
        assert numpy.array_equal(result, data)
Ejemplo n.º 4
0
def test_viewer_open():
    """Test that a plugin to returning an image adds stuff to the viewer."""
    viewer = ViewerModel()
    assert len(viewer.layers) == 0
    viewer.open('mock_path.tif')
    assert len(viewer.layers) == 1
    # The name should be taken from the path name, stripped of extension
    assert viewer.layers[0].name == 'mock_path'

    # stack=True also works... and very long names are truncated
    viewer.open('mock_path.tif', stack=True)
    assert len(viewer.layers) == 2
    assert viewer.layers[1].name.startswith('mock_path')

    expected_source = Source(path='mock_path.tif', reader_plugin='testimpl')
    assert all(lay.source == expected_source for lay in viewer.layers)
Ejemplo n.º 5
0
def test_add_layers_with_plugins_and_kwargs(layer_data, kwargs):
    """Test that _add_layers_with_plugins kwargs override plugin kwargs.

    see also: napari.components._test.test_prune_kwargs
    """
    with patch(
        "napari.plugins.io.read_data_with_plugins",
        MagicMock(return_value=(layer_data, _testimpl)),
    ):

        v = ViewerModel()
        v._add_layers_with_plugins('mock_path', kwargs=kwargs)
        expected_source = Source(path='mock_path', reader_plugin='testimpl')
        for layer in v.layers:
            for key, val in kwargs.items():
                assert getattr(layer, key) == val
                # if plugins don't provide "name", it falls back to path name
                if 'name' not in kwargs:
                    assert layer.name.startswith('mock_path')
            assert layer.source == expected_source
Ejemplo n.º 6
0
    def test_get_channels_from_layer_source(self, mock_aics_image: Mock):
        # Arrange
        mock_image = create_autospec(AICSImage)

        mock_aics_image.return_value = mock_image
        img_path = "/path/to/image.tiff"
        layer = MockLayer(name="Test", source=Source(path=img_path, reader_plugin="builtins"))

        mock_channels = Mock(return_value=["Test1", "Test2", "Test3"])
        mock_image.channel_names = mock_channels.return_value

        # Act
        channels = self._layer_reader.get_channels(layer)

        # Assert
        assert channels is not None
        assert len(channels) == 3
        assert "Test1" == channels[0].name
        assert "Test2" == channels[1].name
        assert "Test3" == channels[2].name
        mock_aics_image.assert_called_with(img_path)
Ejemplo n.º 7
0
def test_source_context():
    """Test nested contexts, overrides, and resets."""

    assert current_source() == Source()
    # everything created within this context will have this sample source
    with layer_source(sample=('samp', 'name')):
        assert current_source() == Source(sample=('samp', 'name'))
        # nested contexts override previous ones
        with layer_source(path='a', reader_plugin='plug'):
            assert current_source() == Source(path='a',
                                              reader_plugin='plug',
                                              sample=('samp', 'name'))
            # note the new path now...
            with layer_source(path='b'):
                assert current_source() == Source(path='b',
                                                  reader_plugin='plug',
                                                  sample=('samp', 'name'))
                # as we exit the contexts, they should undo their assignments
            assert current_source() == Source(path='a',
                                              reader_plugin='plug',
                                              sample=('samp', 'name'))
        assert current_source() == Source(sample=('samp', 'name'))
    assert current_source() == Source()
Ejemplo n.º 8
0
def test_sample_hook(test_plugin_manager, monkeypatch):

    viewer = ViewerModel()

    test_plugin_manager.project_name = 'napari'
    test_plugin_manager.add_hookspecs(plugins.hook_specifications)
    hook = test_plugin_manager.hook.napari_provide_sample_data
    hook.call_historic(
        result_callback=plugins.register_sample_data, with_impl=True
    )

    registered = {}
    monkeypatch.setattr(plugins, "_sample_data", registered)

    with pytest.raises(KeyError) as e:
        viewer.open_sample('test_plugin', 'random data')
    assert (
        "Plugin 'test_plugin' does not provide sample data named 'random data'"
        in str(e)
    )

    def _generate_random_data(shape=(512, 512)):
        data = np.random.rand(*shape)
        return [(data, {'name': 'random data'})]

    LOGO = Path(napari.__file__).parent / 'resources' / 'logo.png'

    class test_plugin:
        @napari_hook_implementation
        def napari_provide_sample_data():
            return {
                'random data': _generate_random_data,
                'napari logo': LOGO,
                'samp_key': {
                    'data': _generate_random_data,
                    'display_name': 'I look gorgeous in the menu!',
                },
            }

    test_plugin_manager.register(test_plugin)

    reg = registered['test_plugin']
    assert reg['random data']['data'] == _generate_random_data
    assert reg['random data']['display_name'] == 'random data'
    assert reg['napari logo']['data'] == LOGO
    assert reg['napari logo']['display_name'] == 'napari logo'
    assert reg['samp_key']['data'] == _generate_random_data
    assert reg['samp_key']['display_name'] == 'I look gorgeous in the menu!'

    assert len(viewer.layers) == 0
    viewer.open_sample('test_plugin', 'random data')
    assert viewer.layers[-1].source == Source(
        path=None, reader_plugin=None, sample=('test_plugin', 'random data')
    )
    assert len(viewer.layers) == 1
    viewer.open_sample('test_plugin', 'napari logo')
    assert viewer.layers[-1].source == Source(
        path=str(LOGO),
        reader_plugin='builtins',
        sample=('test_plugin', 'napari logo'),
    )
    assert len(viewer.layers) == 2
    viewer.open_sample('test_plugin', 'samp_key')
    assert viewer.layers[-1].source == Source(
        sample=('test_plugin', 'samp_key')
    )
    assert len(viewer.layers) == 3

    # test calling with kwargs
    viewer.open_sample('test_plugin', 'samp_key', shape=(256, 256))
    assert len(viewer.layers) == 4
    assert viewer.layers[-1].source == Source(
        sample=('test_plugin', 'samp_key')
    )
Ejemplo n.º 9
0
def test_sample_hook(napari_plugin_manager):

    viewer = ViewerModel()
    napari_plugin_manager.discover_sample_data()

    with pytest.raises(KeyError) as e:
        viewer.open_sample('test_plugin', 'random data')

        print([str(e)])
    assert (
        "Plugin 'test_plugin' does not provide sample data named 'random data'"
        in str(e))

    def _generate_random_data(shape=(512, 512)):
        data = np.random.rand(*shape)
        return [(data, {'name': 'random data'})]

    LOGO = Path(napari.__file__).parent / 'resources' / 'logo.png'

    class test_plugin:
        @napari_hook_implementation
        def napari_provide_sample_data():
            return {
                'random data': _generate_random_data,
                'napari logo': LOGO,
                'samp_key': {
                    'data': _generate_random_data,
                    'display_name': 'I look gorgeous in the menu!',
                },
            }

    napari_plugin_manager.register(test_plugin)

    reg = napari_plugin_manager._sample_data['test_plugin']
    assert reg['random data']['data'] == _generate_random_data
    assert reg['random data']['display_name'] == 'random data'
    assert reg['napari logo']['data'] == LOGO
    assert reg['napari logo']['display_name'] == 'napari logo'
    assert reg['samp_key']['data'] == _generate_random_data
    assert reg['samp_key']['display_name'] == 'I look gorgeous in the menu!'

    assert len(viewer.layers) == 0
    viewer.open_sample('test_plugin', 'random data')
    assert viewer.layers[-1].source == Source(path=None,
                                              reader_plugin=None,
                                              sample=('test_plugin',
                                                      'random data'))
    assert len(viewer.layers) == 1
    viewer.open_sample('test_plugin', 'napari logo')
    assert viewer.layers[-1].source == Source(
        path=str(LOGO),
        reader_plugin='builtins',
        sample=('test_plugin', 'napari logo'),
    )
    assert len(viewer.layers) == 2
    viewer.open_sample('test_plugin', 'samp_key')
    assert viewer.layers[-1].source == Source(sample=('test_plugin',
                                                      'samp_key'))
    assert len(viewer.layers) == 3

    # test calling with kwargs
    viewer.open_sample('test_plugin', 'samp_key', shape=(256, 256))
    assert len(viewer.layers) == 4
    assert viewer.layers[-1].source == Source(sample=('test_plugin',
                                                      'samp_key'))
Ejemplo n.º 10
0
def test_layer_source():
    """Test basic layer source assignment mechanism"""
    with layer_source(path='some_path', reader_plugin='builtins'):
        points = Points()

    assert points.source == Source(path='some_path', reader_plugin='builtins')