def test_basic(self): t = Theme(json={}) d = Document() d._old_theme = t beu._unset_temp_theme(d) assert d.theme is t assert not hasattr(d, "_old_theme")
def test_output(self): p1 = Model() p2 = Model() d = Document() d.add_root(p1) d.add_root(p2) out = beu.standalone_docs_json([p1, p2]) expected = beu.standalone_docs_json_and_render_items([p1, p2])[0] assert list(out.values()) ==list(expected.values())
def test_single_model_with_document(self): # should use existing doc in with-block p = Model() d = Document() orig_theme = d.theme d.add_root(p) with beu.OutputDocumentFor([p], apply_theme=beu.FromCurdoc): assert p.document is d assert d.theme is curdoc().theme assert p.document is d assert d.theme is orig_theme
def test_with_doc_in_child_raises_error(self): doc = Document() p1 = Model() p2 = SomeModelInTestObjects(child=Model()) doc.add_root(p2.child) assert p1.document is None assert p2.document is None assert p2.child.document is doc with pytest.raises(RuntimeError) as e: with beu.OutputDocumentFor([p1, p2]): pass assert "already in a doc" in str(e)
def test_passing_doc(self): p1 = Model() d = Document() d.add_root(p1) docs_json, render_items = beu.standalone_docs_json_and_render_items([d]) doc = list(docs_json.values())[0] assert doc['title'] == "Bokeh Application" assert doc['version'] == __version__ assert len(doc['roots']['root_ids']) == 1 assert len(doc['roots']['references']) == 1 assert doc['roots']['references'] == [{'attributes': {}, 'id': str(p1._id), 'type': 'Model'}] assert len(render_items) == 1
def test_without_document_lock(): d = Document() assert curdoc() is not d curdoc_from_cb = [] @locking.without_document_lock def cb(): curdoc_from_cb.append(curdoc()) callback_obj = d.add_next_tick_callback(cb) callback_obj.callback() assert callback_obj.callback.nolock == True assert len(curdoc_from_cb) == 1 assert curdoc_from_cb[0]._doc is d assert isinstance(curdoc_from_cb[0], locking.UnlockedDocumentProxy)
def test_log_warning_if_python_event_callback(self, caplog): d = Document() m1 = EmbedTestUtilModel() c1 = _GoodEventCallback() d.add_root(m1) m1.on_event(Tap, c1) assert len(m1._event_callbacks) != 0 with caplog.at_level(logging.WARN): beu.standalone_docs_json_and_render_items(m1) assert len(caplog.records) == 1 assert caplog.text != ''
def test_delgation(self, mock_sdjari): p1 = Model() p2 = Model() d = Document() d.add_root(p1) d.add_root(p2) # ignore error unpacking None mock result, just checking to see that # standalone_docs_json_and_render_items is called as expected try: beu.standalone_docs_json([p1, p2]) except ValueError: pass mock_sdjari.assert_called_once_with([p1, p2])
def test_top_level_same_doc(self): d = Document() p1 = Model() p2 = Model() d.add_root(p1) d.add_root(p2) beu._create_temp_doc([p1, p2]) assert isinstance(p1.document, Document) assert p1.document is not d assert isinstance(p2.document, Document) assert p2.document is not d assert p2.document == p1.document
def test_list_of_model_same_as_roots(self): # should use existing doc in with-block p1 = Model() p2 = Model() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1, p2], apply_theme=beu.FromCurdoc): assert p1.document is d assert p2.document is d assert d.theme is curdoc().theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme
def test_with_events(self, mock_comms): mock_comm = MagicMock() mock_send = MagicMock(return_value="junk") mock_comm.send = mock_send mock_comms.return_value = mock_comm d = Document() handle = binb.CommsHandle("comms", d) d.title = "foo" binb.push_notebook(d, None, handle) assert mock_comms.call_count > 0 assert mock_send.call_count == 3 # sends header, metadata, then content assert json.loads(mock_send.call_args[0][0]) == {u"events": [{u"kind": u"TitleChanged", u"title": u"foo"}], u"references": []} assert mock_send.call_args[1] == {}
def test_other_attrs_raise() -> None: d = locking.UnlockedDocumentProxy(Document()) assert curdoc() is not d for attr in (set(dir(d._doc)) - set(dir(d))) | {'foo'}: with pytest.raises(AttributeError) as e: getattr(d, attr) assert e.value.args[0] == locking.UNSAFE_DOC_ATTR_USAGE_MSG
def test_basic(self) -> None: t = Theme(json={}) d = Document() beu._themes[d] = t beu._unset_temp_theme(d) assert d.theme is t assert d not in beu._themes
def test_list_of_model_same_as_roots_with_always_new(self): # should use new temp doc for everything inside with-block p1 = Model() p2 = Model() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1, p2], always_new=True): assert p1.document is not d assert p2.document is not d assert p1.document is p2.document assert p2.document.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme
def test_list_of_model_subset_roots(self): # should use new temp doc for subset inside with-block p1 = Model() p2 = Model() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1], apply_theme=beu.FromCurdoc): assert p1.document is not d assert p2.document is d assert p1.document.theme is curdoc().theme assert p2.document.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme
def test_child_docs(self): d = Document() p1 = Model() p2 = SomeModelInTestObjects(child=Model()) d.add_root(p2.child) beu._create_temp_doc([p1, p2]) assert isinstance(p1.document, Document) assert p1.document is not d assert isinstance(p2.document, Document) assert p2.document is not d assert isinstance(p2.child.document, Document) assert p2.child.document is not d assert p2.document == p1.document assert p2.document == p2.child.document
def test_apply_theme(self) -> None: t = Theme(json={}) d = Document() orig = d.theme beu._set_temp_theme(d, t) assert d._old_theme is orig assert d.theme is t
def test_list_of_model_subset_roots(self) -> None: # should use new temp doc for subset inside with-block p1 = SomeModel() p2 = SomeModel() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1], apply_theme=Theme(json={})): assert p1.document is not d assert p2.document is d assert p1.document.theme is not orig_theme assert p2.document.theme is orig_theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme
def test_list_of_model_same_as_roots_with_always_new(self): # should use new temp doc for everything inside with-block p1 = Model() p2 = Model() d = Document() orig_theme = d.theme d.add_root(p1) d.add_root(p2) with beu.OutputDocumentFor([p1, p2], always_new=True, apply_theme=beu.FromCurdoc): assert p1.document is not d assert p2.document is not d assert p1.document is p2.document assert p2.document.theme is curdoc().theme assert p1.document is d assert p2.document is d assert d.theme is orig_theme
def test_child_docs(self) -> None: d = Document() p1 = SomeModel() p2 = OtherModel(child=SomeModel()) d.add_root(p2.child) beu._create_temp_doc([p1, p2]) assert isinstance(p1.document, Document) assert p1.document is not d assert isinstance(p2.document, Document) assert p2.document is not d assert isinstance(p2.child.document, Document) assert p2.child.document is not d assert p2.document == p1.document assert p2.document == p2.child.document
def test_show_doc_no_server(mock_notebook_content, mock__publish_display_data, mock_get_comms): mock_get_comms.return_value = "comms" s = State() d = Document() mock_notebook_content.return_value = ["notebook_script", "notebook_div", d] class Obj(object): id = None def references(self): return [] assert mock__publish_display_data.call_count == 0 binb.show_doc(Obj(), s, True) expected_args = ({ 'application/javascript': 'notebook_script', 'application/vnd.bokehjs_exec.v0+json': '' }, ) expected_kwargs = { 'metadata': { 'application/vnd.bokehjs_exec.v0+json': { 'id': None } } } assert d._hold is not None assert mock__publish_display_data.call_count == 2 # two mime types assert mock__publish_display_data.call_args[0] == expected_args assert mock__publish_display_data.call_args[1] == expected_kwargs
def updateText(doc: Document, sourceBuySell, sourceVolume, psOrders, psDataSource, psPressure, suuData): dt = doc.get_model_by_name("divText") text = f"Số lượng Hose data point đã scraped được: <br/> {len(sourceBuySell.data['buyPressure'])}<br/>" text += f"Số order phái sinh đã match trong ngày: <br/>{len(psOrders['index'])} <br/>" text += f"Dư mua: {sourceBuySell.data['buyPressure'][-1]:.2f}               " text += f"Dư bán: {sourceBuySell.data['sellPressure'][-1]:.2f} <br/>" # TODO: add Aggregate nnBuy & nnSell # text += f"NN mua(total): {sourceBuySell.iloc[-1]['nnBuy']:.2f}       " # text += f"NN bán(total): {idf.iloc[-1]['nnSell']:.2f} <br/>" ############################################ HOSE Indicators ############################################ currentSource: ColumnDataSource = doc.get_model_by_name("glyphBuyPressure").data_source # upBuySell n_recent_buysell = len(sourceBuySell.data['buyPressure']) n_old_buysell = len(currentSource.data['buyPressure']) numHoseUpdates = n_recent_buysell - n_old_buysell hoseUpdate = {key: sourceBuySell.data[key][n_old_buysell: n_recent_buysell] for key in sourceBuySell.data.keys()} currentSource.stream(hoseUpdate) text += f"<br/><br/>Số data-points mới cho HOSE chưa được cập nhật: <br/>{numHoseUpdates}<br/>" ############################################### Ps Candles ############################################## psSource: ColumnDataSource = doc.get_model_by_name("glyphOHLCSegment").data_source nPSCandles = len(psSource.data['open']) nPSOrders = len(psSource.data['open']) # TODO: fixed this num thing nPSOrders = psSource.data['num'][0] nUnupdatedPSOrders = len(psOrders) - nPSOrders text += f"Số data-point mới cho Phái Sinh chưa được cập nhật: <br/> {len(psDataSource.data['index']) - nPSCandles}<br/>" # update if nUnupdatedPSOrders > 0: pass ############################################### Ps Pressure ############################################## if (datetime.now().hour * 60 + datetime.now().minute) > 14 * 60 + 30: dt.text = text return text += f"psBuyPressure:   { psPressure['psBuyPressure']:.2f} <br/>psSellPressure:   {psPressure['psSellPressure']:.2f} <br/>" text += f"buyVolumes: {psPressure['volBuys']}    (total {psPressure['totalVolBuys']}) <br/> " text += f"sellVolumes: {psPressure['volSells']}    (total {psPressure['totalVolSells']}) <br/> " ############################################### Suu ############################################## text += f"""<br/>foreignerBuyVolume: {suuData["foreignerBuyVolume"]},    foreignerSellVolume {suuData["foreignerSellVolume"]}<br/> """ text += f"""totalBidVolume: {suuData["totalBidVolume"]},    totalOfferVolume {suuData["totalOfferVolume"]}<br/><br/>""" text += f"""Net BU-SD: {suuData['python']['Net BU-SD']} ({timeAgo(suuData)} s ago)""" dt.text = text
def test_passing_doc(self): p1 = Model() d = Document() d.add_root(p1) docs_json, render_items = beu.standalone_docs_json_and_render_items( [d]) doc = list(docs_json.values())[0] assert doc['title'] == "Bokeh Application" assert doc['version'] == __version__ assert len(doc['roots']['root_ids']) == 1 assert len(doc['roots']['references']) == 1 assert doc['roots']['references'] == [{ 'attributes': {}, 'id': str(p1.id), 'type': 'Model' }] assert len(render_items) == 1
def test_no_events(self, mock_comms): mock_comms.return_value = MagicMock() d = Document() handle = binb.CommsHandle("comms", d) binb.push_notebook(d, None, handle) assert mock_comms.call_count == 0
def test_suppress_warnings(self, caplog): d = Document() m1 = EmbedTestUtilModel() c1 = _GoodPropertyCallback() c2 = _GoodEventCallback() d.add_root(m1) m1.on_change('name', c1) assert len(m1._callbacks) != 0 m1.on_event(Tap, c2) assert len(m1._event_callbacks) != 0 with caplog.at_level(logging.WARN): beu.standalone_docs_json_and_render_items(m1, suppress_callback_warning=True) assert len(caplog.records) == 0 assert caplog.text == ''
def test_apply_from_curdoc(self): t = Theme(json={}) curdoc().theme = t d = Document() orig = d.theme beu._set_temp_theme(d, beu.FromCurdoc) assert d._old_theme is orig assert d.theme is t
def test_without_document_lock_accepts_async_function() -> None: i = 0 d = Document() @locking.without_document_lock async def cb(): nonlocal i await asyncio.sleep(0.1) i += 1 callback_obj = d.add_next_tick_callback(cb) loop = asyncio.get_event_loop() loop.run_until_complete(callback_obj.callback()) assert callback_obj.callback.nolock == True assert i == 1
def test_error_on_mixed_list(self): p = SomeModel() d = Document() orig_theme = d.theme with pytest.raises(ValueError) as e: with beu.OutputDocumentFor([p, d]): pass assert str(e.value).endswith(_ODFERR) assert d.theme is orig_theme
def test_list_of_models_different_docs(self): # should use new temp doc for eveything inside with-block d = Document() orig_theme = d.theme p1 = SomeModel() p2 = SomeModel() d.add_root(p2) assert p1.document is None assert p2.document is not None with beu.OutputDocumentFor([p1, p2], apply_theme=beu.FromCurdoc): assert p1.document is not None assert p2.document is not None assert p1.document is not d assert p2.document is not d assert p1.document == p2.document assert p1.document.theme is curdoc().theme assert p1.document is None assert p2.document is not None assert p2.document.theme is orig_theme
def test_with_docs(self): d1 = Document() d2 = Document() p1 = SomeModel() d1.add_root(p1) p2 = OtherModel(child=SomeModel()) d2.add_root(p2.child) beu._create_temp_doc([p1, p2]) beu._dispose_temp_doc([p1, p2]) assert p1.document is d1 assert p2.document is None assert p2.child.document is d2
def test_list_of_models_different_docs(self): # should use new temp doc for eveything inside with-block d = Document() orig_theme = d.theme p1 = Model() p2 = Model() d.add_root(p2) assert p1.document is None assert p2.document is not None with beu.OutputDocumentFor([p1, p2], apply_theme=beu.FromCurdoc): assert p1.document is not None assert p2.document is not None assert p1.document is not d assert p2.document is not d assert p1.document == p2.document assert p1.document.theme is curdoc().theme assert p1.document is None assert p2.document is not None assert p2.document.theme is orig_theme
def test_with_events(self, mock_comms: PropertyMock) -> None: mock_comm = MagicMock() mock_send = MagicMock(return_value="junk") mock_comm.send = mock_send mock_comms.return_value = mock_comm d = Document() handle = binb.CommsHandle("comms", d) d.title = "foo" binb.push_notebook(document=d, handle=handle) assert mock_comms.call_count > 0 assert mock_send.call_count == 3 # sends header, metadata, then content assert json.loads(mock_send.call_args[0][0]) == { "events": [{ "kind": "TitleChanged", "title": "foo" }], } assert mock_send.call_args[1] == {}
def test_with_events(self, mock_comms): mock_comm = MagicMock() mock_send = MagicMock(return_value="junk") mock_comm.send = mock_send mock_comms.return_value = mock_comm d = Document() handle = binb.CommsHandle("comms", d) d.title = "foo" binb.push_notebook(d, None, handle) assert mock_comms.call_count > 0 assert mock_send.call_count == 3 # sends header, metadata, then content assert json.loads(mock_send.call_args[0][0]) == { u"events": [{ u"kind": u"TitleChanged", u"title": u"foo" }], u"references": [] } assert mock_send.call_args[1] == {}
def test_top_level_different_doc(self): d1 = Document() d2 = Document() p1 = SomeModel() p2 = SomeModel() d1.add_root(p1) d2.add_root(p2) beu._create_temp_doc([p1, p2]) assert isinstance(p1.document, Document) assert p1.document is not d1 assert isinstance(p2.document, Document) assert p2.document is not d2 assert p2.document == p1.document
def test_next_tick_callback_works(): d = locking.UnlockedDocumentProxy(Document()) assert curdoc() is not d curdoc_from_cb = [] def cb(): curdoc_from_cb.append(curdoc()) callback_obj = d.add_next_tick_callback(cb) callback_obj.callback() assert len(curdoc_from_cb) == 1 assert curdoc_from_cb[0] is d._doc def cb2(): pass callback_obj = d.add_next_tick_callback(cb2) d.remove_next_tick_callback(callback_obj)
def main(doc: Document) -> None: from bokeh.layouts import layout from bokeh.models import Button from .bokeh_visualiser import main as plot repo_path = TextInput(title='Repository path:', value='../bokeh') include_files = TextInput(title='Include files:', value='.py .js') exclude_files = TextInput(title='Exclude files:', value='.csv') limit = TextInput(title='Top contributors (0-9):', value='9') use_cache = Toggle(label='Use cache (ignores include/exclude)', active=True) visualise = Button(label='Go', button_type='primary') visualise.on_click(lambda: plot( doc, get_path_input(repo_path), get_tokens_input(include_files), get_tokens_input(exclude_files), get_count_input(limit), logged_get_toggle_input(use_cache), )) doc.add_root( layout([[repo_path, include_files, exclude_files, limit], [use_cache, visualise]]))
def test_other_attrs_raise(): d = locking.UnlockedDocumentProxy(Document()) assert curdoc() is not d with pytest.raises(RuntimeError) as e: d.foo assert str( e ) == "Only add_next_tick_callback may be used safely without taking the document lock; " "to make other changes to the document, add a next tick callback and make your changes " "from that callback." for attr in dir(d._doc): if attr in ["add_next_tick_callback", "remove_next_tick_callback"]: continue with pytest.raises(RuntimeError) as e: getattr(d, "foo")
def updateDoc(doc: Document): #if DEBUG: print(f"updated {doc}") sourceBuySell, sourceVolume = requestHoseData() ###################### Hose Buy, Sell ####################### sourceBS = doc.get_model_by_name("glyphSellPressure").data_source lsource = len(sourceBS.data['index']) lnew = len(sourceBuySell.data['index']) if lnew > lsource: hoseUpdate = {key: sourceBuySell.data[key][lsource: lnew] for key in sourceBuySell.data.keys()} sourceBS.stream(hoseUpdate) ################# Liquidity * nnBuy, nnSell ################# sourceVol = doc.get_model_by_name("glyphTotalValue").data_source updateSource(sourceVol , sourceVolume) #update ######################### ohlcCandles ######################### psOrders, psDataSource, psPressure = requestPSData() sourcePs = doc.get_model_by_name("glyphOHLCSegment").data_source updateSource(sourcePs, psDataSource) ######################### Text Display ######################### suuData = None updateText(doc, sourceBuySell, sourceVolume, psOrders, psDataSource, psPressure, suuData = fetchSuuData())
def test_with_docs(self): d1 = Document() d2 = Document() p1 = Model() d1.add_root(p1) p2 = SomeModelInTestObjects(child=Model()) d2.add_root(p2.child) beu._create_temp_doc([p1, p2]) beu._dispose_temp_doc([p1, p2]) assert p1.document is d1 assert p2.document is None assert p2.child.document is d2
def test_top_level_different_doc(self): d1 = Document() d2 = Document() p1 = Model() p2 = Model() d1.add_root(p1) d2.add_root(p2) beu._create_temp_doc([p1, p2]) assert isinstance(p1.document, Document) assert p1.document is not d1 assert isinstance(p2.document, Document) assert p2.document is not d2 assert p2.document == p1.document
def test_no_old_theme(self): d = Document() orig = d.theme beu._unset_temp_theme(d) assert d.theme is orig assert not hasattr(d, "_old_theme")
def test_apply_None(self): d = Document() orig = d.theme beu._set_temp_theme(d, None) assert d._old_theme is orig assert d.theme is orig
def update(self, new_data, doc: Document) -> None: new = {"acc": [new_data[0]], "step": [new_data[1]]} # add_next_tick_callback() can be used safely without taking the document lock doc.add_next_tick_callback(lambda: self.source.stream(new))
def attachDocToServer(doc: Document): global page, sourceVolume, sourceBuySell page, activate, sourceBuySell, sourceVolume = makeMasterPlot() doc.add_root(column(page)) docs.append(doc) activate()
def save(panel, filename, title=None, resources=None, template=None, template_variables=None, embed=False, max_states=1000, max_opts=3, embed_json=False, json_prefix='', save_path='./', load_path=None, progress=True): """ Saves Panel objects to file. Arguments --------- panel: Viewable The Panel Viewable to save to file filename: string or file-like object Filename to save the plot to title: string Optional title for the plot resources: bokeh resources One of the valid bokeh.resources (e.g. CDN or INLINE) template: template file, as used by bokeh.file_html. If None will use bokeh defaults template_variables: template_variables file dict, as used by bokeh.file_html embed: bool Whether the state space should be embedded in the saved file. max_states: int The maximum number of states to embed max_opts: int The maximum number of states for a single widget embed_json: boolean (default=True) Whether to export the data to json files json_prefix: str (default='') Prefix for the randomly json directory save_path: str (default='./') The path to save json files to load_path: str (default=None) The path or URL the json files will be loaded from. progress: boolean (default=True) Whether to report progress """ from ..pane import PaneBase if isinstance(panel, PaneBase) and len(panel.layout) > 1: panel = panel.layout as_png = isinstance(filename, string_types) and filename.endswith('png') doc = Document() comm = Comm() with config.set(embed=embed): with swap_html_model(as_png): model = panel.get_root(doc, comm) if embed: embed_state(panel, model, doc, max_states, max_opts, embed_json, json_prefix, save_path, load_path, progress) else: add_to_doc(model, doc, True) if as_png: save_png(model, filename=filename) return elif isinstance(filename, string_types) and not filename.endswith('.html'): filename = filename + '.html' kwargs = {} if title is None: title = 'Panel' if resources is None: resources = CDN if template: kwargs['template'] = template if template_variables: kwargs['template_variables'] = template_variables html = file_html(doc, resources, title, **kwargs) if hasattr(filename, 'write'): html = decode_utf8(html) if isinstance(filename, io.BytesIO): html = html.encode('utf-8') filename.write(html) return with io.open(filename, mode="w", encoding="utf-8") as f: f.write(decode_utf8(html))