Skip to content

Commit 438adee

Browse files
authored
Merge pull request #290 from vpython/fix/gobj-size-derived
fix(graph): gcurve/gdots constructor honours size= (#287)
2 parents f9a2aba + 521e9ec commit 438adee

2 files changed

Lines changed: 137 additions & 0 deletions

File tree

vpython/test/test_gobj_size.py

Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
"""gcurve/gdots constructor `size=` must reach the browser.
2+
3+
`gobj.size` is DERIVED from `_radius`, so `gobj.setup`'s `setattr(self,'_'+a,val)`
4+
convention wrote a dead `_size` and the send loop shipped the default. See
5+
https://github.com/vpython/vpython-jupyter/issues/287.
6+
7+
These tests drive `gobj.setup` directly against a stub so they need no transport,
8+
no browser and no event loop — the bug and its fix are entirely in that method.
9+
"""
10+
import sys
11+
import types
12+
13+
import pytest
14+
15+
16+
@pytest.fixture()
17+
def gobj_cls(monkeypatch):
18+
"""Import vpython.vpython far enough to reach gobj, with the transport faked.
19+
20+
Importing the PACKAGE would build a canvas and select a transport; importing
21+
the module alone is enough, since gobj.setup only touches baseObj bookkeeping.
22+
"""
23+
saved = {k: v for k, v in sys.modules.items() if k.startswith('vpython')}
24+
for k in list(sys.modules):
25+
if k.startswith('vpython'):
26+
del sys.modules[k]
27+
28+
# `vpython/__init__.py` imports pkg_resources (setuptools), which is absent
29+
# from a bare CPython and from wasm builds. Faked rather than depended on so
30+
# this test does not need setuptools installed to run.
31+
if 'pkg_resources' not in sys.modules:
32+
pkg = types.ModuleType('pkg_resources')
33+
34+
class _DistNotFound(Exception):
35+
pass
36+
37+
# Must REPORT a version rather than raise: __init__ swallows
38+
# DistributionNotFound and leaves __version__ unset, and vpython.py
39+
# then fails on `from vpython import __version__`.
40+
def _get_distribution(name):
41+
return types.SimpleNamespace(version='0.0.0-test')
42+
43+
pkg.DistributionNotFound = _DistNotFound
44+
pkg.get_distribution = _get_distribution
45+
monkeypatch.setitem(sys.modules, 'pkg_resources', pkg)
46+
47+
# `scene = canvas()` runs at package import, but canvas construction sets
48+
# baseObj._canvas_constructing, which SKIPS the transport selection — so no
49+
# websocket/Jupyter machinery is reached and these fakes are enough.
50+
js = types.ModuleType('js')
51+
js.__trinket_vpython_send = lambda s: None
52+
ffi = types.ModuleType('pyodide.ffi'); ffi.create_proxy = lambda f: f
53+
pyo = types.ModuleType('pyodide'); pyo.ffi = ffi
54+
monkeypatch.setitem(sys.modules, 'js', js)
55+
monkeypatch.setitem(sys.modules, 'pyodide', pyo)
56+
monkeypatch.setitem(sys.modules, 'pyodide.ffi', ffi)
57+
58+
try:
59+
from vpython import vpython as vp
60+
yield vp
61+
finally:
62+
for k in list(sys.modules):
63+
if k.startswith('vpython'):
64+
del sys.modules[k]
65+
sys.modules.update(saved)
66+
67+
68+
def _make(vp, cls_name, **kwargs):
69+
"""Run gobj.setup for one constructor without a live transport.
70+
71+
appendcmd is captured so the test can assert on the WIRE package — the thing
72+
the browser actually receives — rather than only on the Python object.
73+
"""
74+
# setup() -> baseObj.__init__() would otherwise select a transport (on a
75+
# desktop that means no_notebook, i.e. an http server + autobahn). Declaring
76+
# the view already constructed skips that; the argument handling under test
77+
# is unaffected by which transport is in place.
78+
vp.baseObj._view_constructed = True
79+
80+
cls = getattr(vp, cls_name)
81+
obj = object.__new__(cls)
82+
sent = []
83+
obj.appendcmd = sent.append
84+
args = dict(kwargs)
85+
args['_objName'] = cls_name
86+
vp.gobj.setup(obj, args)
87+
return obj, (sent[0] if sent else {})
88+
89+
90+
@pytest.mark.parametrize('cls_name', ['gdots', 'gcurve'])
91+
def test_constructor_size_reaches_the_object_and_the_wire(gobj_cls, cls_name):
92+
obj, cmd = _make(gobj_cls, cls_name, size=8)
93+
assert obj.size == 8, 'the constructor argument was dropped'
94+
assert obj.radius == 4, 'size must set the backing _radius (size == 2*radius)'
95+
assert cmd.get('size') == 8, 'the browser was sent the default instead of the argument'
96+
97+
98+
@pytest.mark.parametrize('cls_name', ['gdots', 'gcurve'])
99+
def test_no_dead_private_size_attribute_is_left_behind(gobj_cls, cls_name):
100+
obj, _ = _make(gobj_cls, cls_name, size=8)
101+
assert not hasattr(obj, '_size'), '_size is not the backing store and must not be written'
102+
103+
104+
def test_radius_still_works_and_agrees_with_size(gobj_cls):
105+
obj, cmd = _make(gobj_cls, 'gdots', radius=4)
106+
assert obj.radius == 4
107+
assert obj.size == 8
108+
assert cmd.get('radius') == 4
109+
110+
111+
def test_default_size_is_unchanged_when_not_specified(gobj_cls):
112+
obj, cmd = _make(gobj_cls, 'gdots', color=None) if False else _make(gobj_cls, 'gdots')
113+
assert obj.size == 6 and obj.radius == 3, 'defaults must not move'
114+
assert 'size' not in cmd, 'unspecified attributes are not sent'
115+
116+
117+
def test_the_setter_path_still_works(gobj_cls):
118+
"""Post-construction assignment was never broken; pin it so a fix here
119+
cannot regress it."""
120+
obj, _ = _make(gobj_cls, 'gdots')
121+
obj.addattr = lambda attr: None # setter calls addattr; no transport here
122+
obj.size = 10
123+
assert obj.size == 10 and obj.radius == 5

vpython/vpython.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2168,6 +2168,20 @@ def setup(self, args):
21682168
val = val.idx
21692169
# elif a == 'fast' and _isnotebook and not val:
21702170
# raise AttributeError('"fast = False" is currently not available in a Jupyter notebook.')
2171+
elif a == 'size':
2172+
# `size` is DERIVED from _radius (see the property below), so the
2173+
# `_`+name convention does not apply to it: setattr(self,'_size')
2174+
# writes an attribute nothing ever reads, and the send loop below
2175+
# then reads the property and ships the DEFAULT. gdots(size=8)
2176+
# silently plotted 6-pixel dots.
2177+
#
2178+
# _radius is set directly rather than through the size setter
2179+
# because that setter also calls addattr('radius'), which spins
2180+
# on baseObj.sent — redundant here (this constructor's own cmd
2181+
# already carries the value) and, on a single-threaded host such
2182+
# as Pyodide, a deadlock rather than a wait.
2183+
self._radius = val/2
2184+
continue
21712185
setattr(self, '_'+a, val)
21722186

21732187
cmd = {"cmd": objName, "idx": self.idx}

0 commit comments

Comments
 (0)