from unittest.mock import Mock

import pytest
from pydantic import ValidationError

from napari.utils.events import EventedModel, Selection


def test_selection():
    class T(EventedModel):
        sel: Selection[int]

    t = T(sel=[])
    t.sel.events.current = Mock()
    assert not t.sel.current
    assert not t.sel
    t.sel.add(1)
    t.sel.current = 1
    t.sel.events.current.assert_called_once()

    assert 1 in t.sel
    assert t.sel.current == 1

    assert t.json() == r'{"sel": {"data": [1], "current": 1}}'
    assert T(sel={"data": [1], "current": 1}) == t

    t.sel.remove(1)
    assert not t.sel

    with pytest.raises(ValidationError):
        T(sel=['asdf'])

    with pytest.raises(ValidationError):
        T(sel={"data": [1], "current": 'asdf'})
