Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug in set_state/_lock_property #2256

Merged
merged 3 commits into from
Nov 8, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 41 additions & 1 deletion ipywidgets/widgets/tests/test_set_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,13 @@
from ipython_genutils.py3compat import PY3

import pytest
try:
from unittest import mock
except ImportError:
import mock

from traitlets import Bool, Tuple, List, Instance, CFloat, CInt, Float, Int, TraitError

from traitlets import Bool, Tuple, List, Instance, CFloat, CInt, Float, Int, TraitError, observe

from .utils import setup, teardown

Expand Down Expand Up @@ -211,3 +216,38 @@ def test_set_state_int_to_float():
w.set_state(dict(
i = 3.5
))

def test_property_lock():
# when this widget's value is set to 42, it sets itself to 2, and then back to 42 again (and then stops)
class AnnoyingWidget(Widget):
value = Float().tag(sync=True)
stop = Bool(False)

@observe('value')
def _propagate_value(self, change):
print('_propagate_value', change.new)
if self.stop:
return
if change.new == 42:
self.value = 2
if change.new == 2:
self.stop = True
self.value = 42

widget = AnnoyingWidget(value=1)
assert widget.value == 1

widget._send = mock.MagicMock()
# this mimics a value coming from the front end
widget.set_state({'value': 42})
assert widget.value == 42

# we expect first the {'value': 2.0} state to be send, followed by the {'value': 42.0} state
msg = {'method': 'update', 'state': {'value': 2.0}, 'buffer_paths': []}
call2 = mock.call(msg, buffers=[])

msg = {'method': 'update', 'state': {'value': 42.0}, 'buffer_paths': []}
call42 = mock.call(msg, buffers=[])

calls = [call2, call42]
widget._send.assert_has_calls(calls)
5 changes: 5 additions & 0 deletions ipywidgets/widgets/widget.py
Original file line number Diff line number Diff line change
Expand Up @@ -479,10 +479,15 @@ def send_state(self, key=None):
"""
state = self.get_state(key=key)
if len(state) > 0:
if self._property_lock: # we need to keep this dict up to date with the front-end values
for name, value in state.items():
if name in self._property_lock:
self._property_lock[name] = value
state, buffer_paths, buffers = _remove_buffers(state)
msg = {'method': 'update', 'state': state, 'buffer_paths': buffer_paths}
self._send(msg, buffers=buffers)


def get_state(self, key=None, drop_defaults=False):
"""Gets the widget state, or a piece of it.

Expand Down