def test_connect_and_reconnect(): try: options = BootOptions(maximum_logins=4) process = options.boot(options.find_scsynth(), 57110) server = Server(port=57110) server.connect() assert server.is_running and not server.is_owner assert server.client_id == 0 assert str(server.query_local_nodes(True)) == normalize( """ NODE TREE 0 group 1 group 2 group 3 group 4 group """ ) server.disconnect() server.connect() assert server.is_running and not server.is_owner assert server.client_id == 1 assert str(server.query_local_nodes(True)) == normalize( """ NODE TREE 0 group 1 group 2 group 3 group 4 group """ ) finally: process.terminate() process.wait()
def test_RealtimeProvider_set_node_3(server): provider = Provider.from_context(server) with provider.at(None): synth_proxy = provider.add_synth() bus_proxy = provider.add_bus() time.sleep(0.01) with server.osc_protocol.capture() as transcript: with provider.at(None): synth_proxy["frequency"] = bus_proxy assert [entry.message.to_list() for entry in transcript ] == [[None, [["/n_set", 1000, "frequency", "c0"]]]] time.sleep(0.01) assert str(server) == normalize(""" NODE TREE 0 group 1 group 1000 default out: 0.0, amplitude: 0.1, frequency: c0, gate: 1.0, pan: 0.5 """) time.sleep(0.01) with server.osc_protocol.capture() as transcript: with provider.at(None): synth_proxy["frequency"] = 443 assert [entry.message.to_list() for entry in transcript ] == [[None, [["/n_set", 1000, "frequency", 443.0]]]] time.sleep(0.01) assert str(server) == normalize(""" NODE TREE 0 group 1 group 1000 default out: 0.0, amplitude: 0.1, frequency: 443.0, gate: 1.0, pan: 0.5 """)
def test_rebuild_document_02(): document = uqbar.book.sphinx.parse_rst(source_b) blocks = uqbar.book.sphinx.collect_literal_blocks(document) extensions = [GraphExtension] node_mapping = uqbar.book.sphinx.interpret_code_blocks( blocks, extensions=extensions) uqbar.book.sphinx.rebuild_document(document, node_mapping) assert normalize(document.pformat()) == normalize(""" <document source="test"> <literal_block xml:space="preserve"> >>> import uqbar.graphs >>> g = uqbar.graphs.Graph() >>> n1 = uqbar.graphs.Node() >>> n2 = uqbar.graphs.Node() >>> g.extend([n1, n2]) >>> e = n1.attach(n2) <literal_block xml:space="preserve"> >>> print(format(g, "graphviz")) digraph G { node_0; node_1; node_0 -> node_1; } <literal_block xml:space="preserve"> >>> uqbar.graphs.Grapher(g)() <graphviz_block layout="dot" xml:space="preserve"> digraph G { node_0; node_1; node_0 -> node_1; } """)
def test_connect_and_reconnect(): try: options = BootOptions(maximum_logins=4) process = options.boot(options.find_scsynth(), 57110) server = Server(port=57110) server.connect() assert server.is_running and not server.is_owner assert server.client_id == 0 assert str(server.query_local_nodes(True)) == normalize(""" NODE TREE 0 group 1 group 2 group 3 group 4 group """) server.disconnect() server.connect() assert server.is_running and not server.is_owner assert server.client_id == 1 assert str(server.query_local_nodes(True)) == normalize(""" NODE TREE 0 group 1 group 2 group 3 group 4 group """) finally: process.terminate() process.wait()
def test_collection_01(test_path): builder = uqbar.apis.APIBuilder([test_path / "fake_package"], test_path / "docs") source_paths = uqbar.apis.collect_source_paths( builder._initial_source_paths) node_tree = builder.build_node_tree(source_paths) assert normalize(str(node_tree)) == normalize(""" None/ fake_package/ fake_package.empty_module fake_package.empty_package/ fake_package.empty_package.empty fake_package.enums fake_package.module fake_package.multi/ fake_package.multi.one fake_package.multi.two """) documenters = list(builder.collect_module_documenters(node_tree)) assert isinstance(documenters[0], uqbar.apis.RootDocumenter) assert [documenter.package_path for documenter in documenters[1:]] == [ "fake_package", "fake_package.empty_module", "fake_package.empty_package", "fake_package.empty_package.empty", "fake_package.enums", "fake_package.module", "fake_package.multi", "fake_package.multi.one", "fake_package.multi.two", ]
def test_sphinx_api_1(app, status, warning): app.build() index_source = pathlib.Path(app.srcdir) / "api" / "index.rst" assert index_source.exists() assert "build succeeded" in status.getvalue() assert "8 added, 0 changed, 0 removed" in status.getvalue() assert "0 added, 0 changed, 0 removed" not in status.getvalue() assert not warning.getvalue().strip() path = pathlib.Path(app.srcdir) / "_build" / "text" / "api" / "index.txt" with path.open() as file_pointer: assert normalize(file_pointer.read()) == normalize(""" API *** * fake_package * enums * module * multi * one * two """) # Build again, confirm that nothing has changed. app.build() assert "0 added, 0 changed, 0 removed" in status.getvalue()
def test_connect_and_reconnect(): try: options = scsynth.Options(maximum_logins=4) protocol = SyncProcessProtocol() protocol.boot(options, scsynth.find(), 57110) server = Server() server.connect(port=57110) assert server.is_running and not server.is_owner assert server.client_id == 0 assert str(server.query_local_nodes(True)) == normalize(""" NODE TREE 0 group 1 group 2 group 3 group 4 group """) server.disconnect() server.connect(port=57110) assert server.is_running and not server.is_owner assert server.client_id == 1 assert str(server.query_local_nodes(True)) == normalize(""" NODE TREE 0 group 1 group 2 group 3 group 4 group """) finally: protocol.quit()
def test_collect_literal_blocks_02(): document = uqbar.book.sphinx.parse_rst(source_b) blocks = uqbar.book.sphinx.collect_literal_blocks(document) expected = [ """ <literal_block xml:space="preserve"> >>> import uqbar.graphs >>> g = uqbar.graphs.Graph() >>> n1 = uqbar.graphs.Node() >>> n2 = uqbar.graphs.Node() >>> g.extend([n1, n2]) >>> e = n1.attach(n2) """, """ <literal_block xml:space="preserve"> >>> print(format(g, "graphviz")) """, """ <literal_block xml:space="preserve"> >>> uqbar.graphs.Grapher(g)() """, ] actual = [normalize(block.pformat()) for block in blocks] expected = [normalize(text) for text in expected] assert actual == expected
def test_system_link_audio_1_sclang(): sc_compiled = SuperColliderSynthDef( "system_link_audio_1", r""" | out=0, in=16, vol=1, level=1, lag=0.05, doneAction=2 | var env = EnvGate(i_level: 0, doneAction:doneAction, curve:'sin') * Lag.kr(vol * level, lag); Out.ar(out, InFeedback.ar(in, 1) * env) """, r"[\kr, \kr, \kr, \kr, \kr, \ir]", ).compile() sc_synthdef = SynthDefDecompiler.decompile_synthdef(sc_compiled) assert normalize(str(sc_synthdef)) == normalize( """ synthdef: name: system_link_audio_1 ugens: - Control.ir: null - Control.kr: null - BinaryOpUGen(MULTIPLICATION).kr/0: left: Control.kr[2:vol] right: Control.kr[3:level] - Lag.kr: lag_time: Control.kr[4:lag] source: BinaryOpUGen(MULTIPLICATION).kr/0[0] - InFeedback.ar: bus: Control.kr[1:in] - Control.kr: null - Control.kr: null - EnvGen.kr: done_action: Control.ir[0:doneAction] envelope[0]: 0.0 envelope[10]: 3.0 envelope[11]: 0.0 envelope[1]: 2.0 envelope[2]: 1.0 envelope[3]: -99.0 envelope[4]: 1.0 envelope[5]: 1.0 envelope[6]: 3.0 envelope[7]: 0.0 envelope[8]: 0.0 envelope[9]: 1.0 gate: Control.kr[0:gate] level_bias: 0.0 level_scale: 1.0 time_scale: Control.kr[0:fadeTime] - BinaryOpUGen(MULTIPLICATION).kr/1: left: EnvGen.kr[0] right: Lag.kr[0] - BinaryOpUGen(MULTIPLICATION).ar: left: InFeedback.ar[0] right: BinaryOpUGen(MULTIPLICATION).kr/1[0] - Out.ar: bus: Control.kr[0:out] source[0]: BinaryOpUGen(MULTIPLICATION).ar[0] """ )
def test_shared_resources(): server_a, server_b = Server(), Server() server_a.boot(maximum_logins=2) server_b.connect() with supriya.SynthDefBuilder(frequency=440) as builder: _ = supriya.ugens.Out.ar( bus=0, source=supriya.ugens.SinOsc.ar(frequency=builder["frequency"]) ) synthdef = builder.build(name="foo") synth = supriya.Synth(synthdef=synthdef) transcript_a = server_a.osc_protocol.capture() transcript_b = server_b.osc_protocol.capture() with transcript_a, transcript_b: synth.allocate(target_node=server_b) time.sleep(0.1) # Wait for all clients to receive /n_go assert synth not in server_a assert synth in server_b assert [ (label, osc_message) for _, label, osc_message in transcript_a if osc_message.address not in ["/status", "/status.reply"] ] == [("R", OscMessage("/n_go", 67109864, 2, -1, -1, 0))] assert [ (label, osc_message) for _, label, osc_message in transcript_b if osc_message.address not in ["/status", "/status.reply"] ] == [ ( "S", OscMessage( "/d_recv", synthdef.compile(), OscMessage("/s_new", "foo", 67109864, 0, 2), ), ), ("R", OscMessage("/n_go", 67109864, 2, -1, -1, 0)), ("R", OscMessage("/done", "/d_recv")), ] # TODO: Server A doesn't actually know what this SynthDef should be. assert str(server_a.root_node) == normalize( """ NODE TREE 0 group 1 group 2 group 67109864 default out: 0.0, amplitude: 0.1, frequency: 440.0, gate: 1.0, pan: 0.5 """ ) assert str(server_b.root_node) == normalize( """ NODE TREE 0 group 1 group 2 group 67109864 foo frequency: 440.0 """ )
def test_str_03(test_path): documenter = uqbar.apis.ClassDocumenter("fake_package.module._PrivateClass") assert normalize(str(documenter)) == normalize( """ .. autoclass:: _PrivateClass :members: :undoc-members: """ )
def test_call(): string_io = io.StringIO() with uqbar.io.RedirectedStreams(string_io, string_io): with pytest.raises(SystemExit): VoxAggregator()("mammals meow --loud") assert normalize(string_io.getvalue()) == normalize( """ MEOW! """ )
def test_interpret_code_blocks_02(): def logger_func(message): messages.append(message) error_message = ("Traceback (most recent call last):\n" ' File "<stdin>", line 1, in <module>\n') if LooseVersion(sys.version.split()[0]) < LooseVersion("3.7"): error_message += "TypeError: must be str, not int\n" else: error_message += 'TypeError: can only concatenate str (not "int") to str\n' messages = [] source = normalize(""" This will interpret happily. :: >>> "1" + 2 Traceback (most recent call last): File "<stdin>", line 1, in <module> {error_message} """.format(error_message=error_message)) document = uqbar.book.sphinx.parse_rst(source) blocks = uqbar.book.sphinx.collect_literal_blocks(document) # This has a traceback, so it passes. uqbar.book.sphinx.interpret_code_blocks(blocks, logger_func=logger_func) assert messages == [error_message] messages[:] = [] source = normalize(""" This will not interpret happily. :: >>> for i in range(1, 4): ... i / 0 ... "This is fine" """) document = uqbar.book.sphinx.parse_rst(source) blocks = uqbar.book.sphinx.collect_literal_blocks(document) with pytest.raises(ConsoleError): # This does not have a traceback, so it fails. uqbar.book.sphinx.interpret_code_blocks(blocks, logger_func=logger_func) assert messages == [("Traceback (most recent call last):\n" ' File "<stdin>", line 2, in <module>\n' "ZeroDivisionError: division by zero\n")] messages[:] = [] # This passes because we force it to. uqbar.book.sphinx.interpret_code_blocks(blocks, allow_exceptions=True, logger_func=logger_func) assert messages == [("Traceback (most recent call last):\n" ' File "<stdin>", line 2, in <module>\n' "ZeroDivisionError: division by zero\n")]
def test_str_01(test_path): documenter = uqbar.apis.SummarizingModuleDocumenter("fake_package.module") assert normalize(str(documenter)) == normalize( """ .. _fake-package--module: module ====== .. automodule:: fake_package.module .. currentmodule:: fake_package.module .. container:: svg-container .. inheritance-diagram:: fake_package :lineage: fake_package.module .. raw:: html <hr/> .. rubric:: Classes :class: section-header .. autosummary:: :nosignatures: ~ChildClass ~PublicClass .. autoclass:: ChildClass :members: :undoc-members: .. autoclass:: PublicClass :members: :undoc-members: .. raw:: html <hr/> .. rubric:: Functions :class: section-header .. autosummary:: :nosignatures: ~public_function .. autofunction:: public_function """ )
def test_rebuild_document_03(): document = uqbar.book.sphinx.parse_rst(source_c) blocks = uqbar.book.sphinx.collect_literal_blocks(document) extensions = [GraphExtension] node_mapping = uqbar.book.sphinx.interpret_code_blocks( blocks, extensions=extensions) uqbar.book.sphinx.rebuild_document(document, node_mapping) assert normalize(document.pformat()) == normalize(""" <document source="test"> <literal_block xml:space="preserve"> >>> import uqbar.graphs >>> g = uqbar.graphs.Graph() >>> n1 = uqbar.graphs.Node() >>> g.append(n1) >>> for i in range(3): ... n2 = uqbar.graphs.Node() ... g.append(n2) ... e = n1.attach(n2) ... uqbar.graphs.Grapher(g)() ... print(i) ... n1 = n2 ... <graphviz_block layout="dot" xml:space="preserve"> digraph G { node_0; node_1; node_0 -> node_1; } <literal_block xml:space="preserve"> 0 <graphviz_block layout="dot" xml:space="preserve"> digraph G { node_0; node_1; node_2; node_0 -> node_1; node_1 -> node_2; } <literal_block xml:space="preserve"> 1 <graphviz_block layout="dot" xml:space="preserve"> digraph G { node_0; node_1; node_2; node_3; node_0 -> node_1; node_1 -> node_2; node_2 -> node_3; } <literal_block xml:space="preserve"> 2 """)
def test_lilypond_error(paths): """ Handle failing LilyPond rendering. """ string_io = StringIO() pytest.helpers.create_score(paths.test_directory_path) material_path = pytest.helpers.create_material(paths.test_directory_path, "test_material") definition_path = material_path.joinpath("definition.py") with open(str(definition_path), "w") as file_pointer: file_pointer.write( normalize(r""" import abjad test_material = abjad.lilypondfile.LilyPondFile.new() test_material.items.append(r'\this-does-not-exist') """)) script = abjadext.cli.ManageMaterialScript() command = ["--illustrate", "test_material"] with uqbar.io.RedirectedStreams(stdout=string_io): with uqbar.io.DirectoryChange(paths.score_path): pytest.helpers.run_script(script, command, expect_error=True) pytest.helpers.compare_strings( actual=string_io.getvalue(), expected=r""" Illustration candidates: 'test_material' ... Illustrating test_score/materials/test_material/ Importing test_score.materials.test_material.definition Abjad runtime: ... second... Writing test_score/materials/test_material/illustration.ly ... OK! Writing test_score/materials/test_material/illustration.pdf ... Failed! """.replace("/", os.path.sep), ) illustration_ly_path = material_path.joinpath("illustration.ly") assert illustration_ly_path.exists() pytest.helpers.compare_lilypond_contents( illustration_ly_path, normalize(r""" \language "english" %! abjad.LilyPondFile._get_format_pieces() \header { %! abjad.LilyPondFile._get_formatted_blocks() tagline = ##f } %! abjad.LilyPondFile._get_formatted_blocks() \layout {} \paper {} \this-does-not-exist """), )
def test_parse_rst_01(): document = uqbar.book.sphinx.parse_rst(source_a) assert normalize(document.pformat()) == normalize(""" <document source="test"> <literal_block xml:space="preserve"> >>> string = 'Hello, world!' <literal_block xml:space="preserve"> >>> for i in range(3): ... string += " {}".format(i) ... <literal_block xml:space="preserve"> >>> print(string) Hello, world! """)
def test_list(): string_io = io.StringIO() with uqbar.io.RedirectedStreams(string_io, string_io): with pytest.raises(SystemExit): VoxAggregator()("list") assert normalize(string_io.getvalue()) == normalize( """ [birds] squawk: speak like a bird [mammals] meow: speak like a cat woof: speak like a dog """ )
def test_python_error_on_illustrate(paths): """ Handle exceptions inside the Python module on __call__(). """ string_io = StringIO() pytest.helpers.create_score(paths.test_directory_path) material_path = pytest.helpers.create_material(paths.test_directory_path, "test_material") definition_path = material_path.joinpath("definition.py") with open(str(definition_path), "w") as file_pointer: file_pointer.write( normalize(r""" class Foo: def __illustrate__(paths): raise TypeError('This is fake.') test_material = Foo() """)) script = abjadext.cli.ManageMaterialScript() command = ["--illustrate", "test_material"] with uqbar.io.RedirectedStreams(stdout=string_io): with uqbar.io.DirectoryChange(paths.score_path): pytest.helpers.run_script(script, command, expect_error=True) pytest.helpers.compare_strings( actual=string_io.getvalue(), expected=r""" Illustration candidates: 'test_material' ... Illustrating test_score/materials/test_material/ Importing test_score.materials.test_material.definition """.replace("/", os.path.sep), )
def test_RealtimeProvider_add_synth_1(server): provider = Provider.from_context(server) seconds = time.time() with server.osc_protocol.capture() as transcript: with provider.at(seconds) as provider_moment: synth_proxy = provider.add_synth(amplitude=0.3, frequency=333) assert synth_proxy == SynthProxy( identifier=1000, provider=provider, synthdef=default, settings=dict(amplitude=0.3, frequency=333), ) assert provider_moment == ProviderMoment( provider=provider, seconds=seconds, bus_settings=[], node_additions=[(synth_proxy, AddAction.ADD_TO_HEAD, server.default_group)], node_removals=[], node_reorderings=[], node_settings=[], ) assert [entry.message.to_list() for entry in transcript] == [[ seconds + provider.latency, [["/s_new", "default", 1000, 0, 1, "amplitude", 0.3, "frequency", 333]], ]] time.sleep(0.1) assert str(server) == normalize(""" NODE TREE 0 group 1 group 1000 default out: 0.0, amplitude: 0.3, frequency: 333.0, gate: 1.0, pan: 0.5 """)
def test_RealtimeProvider_add_group_2(server): provider = Provider.from_context(server) seconds = time.time() with server.osc_protocol.capture() as transcript: with provider.at(None): group_proxy_one = provider.add_group() with provider.at(seconds + 0.01) as provider_moment: group_proxy_two = provider.add_group(target_node=group_proxy_one) assert group_proxy_two == GroupProxy(identifier=1001, provider=provider) assert provider_moment == ProviderMoment( provider=provider, seconds=seconds + 0.01, bus_settings=[], node_additions=[(group_proxy_two, AddAction.ADD_TO_HEAD, group_proxy_one)], node_removals=[], node_reorderings=[], node_settings=[], ) assert [entry.message.to_list() for entry in transcript] == [ [None, [["/g_new", 1000, 0, 1]]], [seconds + 0.01 + provider.latency, [["/g_new", 1001, 0, 1000]]], ] time.sleep(0.1) assert str(server) == normalize(""" NODE TREE 0 group 1 group 1000 group 1001 group """)
def test_python_cannot_illustrate(paths): """ Handle un-illustrables. """ string_io = StringIO() pytest.helpers.create_score(paths.test_directory_path) material_path = pytest.helpers.create_material(paths.test_directory_path, "test_material") definition_path = material_path.joinpath("definition.py") with open(str(definition_path), "w") as file_pointer: file_pointer.write( normalize(r""" test_material = None """)) script = abjadext.cli.ManageMaterialScript() command = ["--illustrate", "test_material"] with uqbar.io.RedirectedStreams(stdout=string_io): with uqbar.io.DirectoryChange(paths.score_path): pytest.helpers.run_script(script, command, expect_error=True) pytest.helpers.compare_strings( actual=string_io.getvalue(), expected=r""" Illustration candidates: 'test_material' ... Illustrating test_score/materials/test_material/ Importing test_score.materials.test_material.definition Cannot illustrate material of type NoneType. """.replace("/", os.path.sep), )
def test_parse_rst_02(): document = uqbar.book.sphinx.parse_rst(source_b) assert normalize(document.pformat()) == normalize(""" <document source="test"> <literal_block xml:space="preserve"> >>> import uqbar.graphs >>> g = uqbar.graphs.Graph() >>> n1 = uqbar.graphs.Node() >>> n2 = uqbar.graphs.Node() >>> g.extend([n1, n2]) >>> e = n1.attach(n2) <literal_block xml:space="preserve"> >>> print(format(g, "graphviz")) <literal_block xml:space="preserve"> >>> uqbar.graphs.Grapher(g)() """)
def test_sphinx_book_text_cached(app, status, warning, rm_dirs): app.build() assert not warning.getvalue().strip() assert app.config["uqbar_book_use_cache"] assert list( app.connection.execute( "SELECT path, hits FROM cache ORDER BY path")) == [ ("fake.Child", 0), ("fake.Child.two", 0), ("fake.GrandParent", 0), ("fake.GrandParent.one", 1), ("fake.GrandParent.three", 3), ("fake.GrandParent.two", 2), ("fake.Outer", 0), ("fake.Outer.Inner", 0), ("fake.Outer.Inner.inner_method", 0), ("fake.Outer.outer_method", 0), ("fake.Parent", 0), ("fake.Parent.one", 1), ("fake.just_a_function", 0), ] assert not warning.getvalue().strip() for filename, expected_content in [ ("api.txt", api_content), ("directives.txt", directives_content), ("index.txt", index_content), ]: path = pathlib.Path(app.srcdir) / "_build" / "text" / filename actual_content = normalize(path.read_text()) assert actual_content == expected_content
def visit_thumbnail_block_html(self, node): template = normalize(""" <a data-lightbox="{group}" href="{target_path}" title="{title}" data-title="{title}" class="{cls}"> <img src="{thumbnail_path}" alt="{alt}"/> </a> """) title = node["title"] classes = " ".join(node["classes"]) group = "group-{}".format(node["group"] if node["group"] else node["uri"]) if node["uri"] in self.builder.images: node["uri"] = os.path.join(self.builder.imgpath, self.builder.images[node["uri"]]) target_path = node["uri"] prefix, suffix = os.path.splitext(target_path) if suffix == ".png": thumbnail_path = target_path else: thumbnail_path = "{}-thumbnail{}".format(prefix, suffix) output = template.format( alt=title, group=group, target_path=target_path, cls=classes, thumbnail_path=thumbnail_path, title=title, ) self.body.append(output) raise SkipNode
def test_RealtimeProvider_add_group_1(server): provider = Provider.from_context(server) seconds = time.time() with server.osc_protocol.capture() as transcript: with provider.at(seconds) as provider_moment: group_proxy = provider.add_group() assert group_proxy == GroupProxy(identifier=1000, provider=provider) assert provider_moment == ProviderMoment( provider=provider, seconds=seconds, bus_settings=[], node_additions=[(group_proxy, AddAction.ADD_TO_HEAD, server.default_group)], node_removals=[], node_reorderings=[], node_settings=[], ) assert [entry.message.to_list() for entry in transcript ] == [[seconds + provider.latency, [["/g_new", 1000, 0, 1]]]] time.sleep(0.1) assert str(server.query()) == normalize(""" NODE TREE 0 group 1 group 1000 group """)
def test_rebuild_document_04(): document = uqbar.book.sphinx.parse_rst(source_d) blocks = uqbar.book.sphinx.collect_literal_blocks(document) extensions = [GraphExtension] node_mapping = uqbar.book.sphinx.interpret_code_blocks( blocks, extensions=extensions) uqbar.book.sphinx.rebuild_document(document, node_mapping) assert normalize(document.pformat()) == normalize(""" <document source="test"> <graphviz_block layout="dot" xml:space="preserve"> digraph G { node_0; node_1; node_0 -> node_1; } """)
class RenderExtension(Extension): template = normalize(""" <audio controls src="{file_path}"> Your browser does not support the <code>audio</code> element. </audio> """) class render_block(General, FixedTextElement): pass @classmethod def setup_console(cls, console, monkeypatch): monkeypatch.setattr( Player, "__call__", lambda self: console.push_proxy( cls(self.renderable, self.render_kwargs)), ) @classmethod def setup_sphinx(cls, app): app.add_node( cls.render_block, html=[cls.visit_block_html, None], latex=[cls.visit_block_latex, None], text=[cls.visit_block_text, cls.depart_block_text], ) def __init__(self, renderable, render_kwargs): self.renderable = pickle.loads(pickle.dumps(renderable)) self.render_kwargs = pickle.loads(pickle.dumps(render_kwargs)) def to_docutils(self): code = "\n".join( textwrap.wrap( base64.b64encode( pickle.dumps( (self.renderable, self.render_kwargs))).decode())) node = self.render_block(code, code) return [node] @classmethod def render(cls, node, output_path): output_path.mkdir(exist_ok=True) renderable, render_kwargs = pickle.loads( base64.b64decode("".join(node[0].split()))) return websafe_audio( renderable.__render__(render_directory_path=output_path, **render_kwargs)) @staticmethod def visit_block_html(self, node): absolute_file_path = RenderExtension.render( node, pathlib.Path(self.builder.outdir) / "_images") relative_file_path = (pathlib.Path(self.builder.imgpath) / absolute_file_path.name) result = RenderExtension.template.format(file_path=relative_file_path) self.body.append(result) raise SkipNode
def test_02_ugens(py_synthdef_02): assert tuple(repr(_) for _ in py_synthdef_02.ugens) == ( "PinkNoise.ar()", "MaxLocalBufs.ir()", "LocalBuf.ir()", "FFT.kr()", "BufFrames.ir()", "LocalBuf.ir()", "PV_Copy.kr()", "PV_BinScramble.kr()", "PV_MagFreeze.kr()", "PV_MagMul.kr()", "IFFT.ar()", "Out.ar()", ) assert str(py_synthdef_02) == normalize(""" synthdef: name: PVCopyTest ugens: - PinkNoise.ar: null - MaxLocalBufs.ir: maximum: 2.0 - LocalBuf.ir/0: channel_count: 1.0 frame_count: MaxLocalBufs.ir[0] - FFT.kr: active: 1.0 buffer_id: LocalBuf.ir/0[0] hop: 0.5 source: PinkNoise.ar[0] window_size: 0.0 window_type: 0.0 - BufFrames.ir: buffer_id: LocalBuf.ir/0[0] - LocalBuf.ir/1: channel_count: 1.0 frame_count: MaxLocalBufs.ir[0] - PV_Copy.kr: pv_chain_a: FFT.kr[0] pv_chain_b: LocalBuf.ir/1[0] - PV_BinScramble.kr: pv_chain: PV_Copy.kr[0] trigger: 0.0 width: 0.2 wipe: 0.0 - PV_MagFreeze.kr: freeze: 0.0 pv_chain: FFT.kr[0] - PV_MagMul.kr: pv_chain_a: PV_BinScramble.kr[0] pv_chain_b: PV_MagFreeze.kr[0] - IFFT.ar: pv_chain: PV_MagMul.kr[0] window_size: 0.0 window_type: 0.0 - Out.ar: bus: 0.0 source[0]: IFFT.ar[0] """)
def test_call_help(): string_io = io.StringIO() with uqbar.io.RedirectedStreams(string_io, string_io): with pytest.raises(SystemExit): VoxAggregator()("mammals meow --help") assert normalize(string_io.getvalue()) == normalize( """ usage: meow-cli [-h] [--version] [--loud] speak like a cat optional arguments: -h, --help show this help message and exit --version show program's version number and exit --loud be adamant """ )
def test_rebuild_document_01(): document = uqbar.book.sphinx.parse_rst(source_a) blocks = uqbar.book.sphinx.collect_literal_blocks(document) node_mapping = uqbar.book.sphinx.interpret_code_blocks(blocks) uqbar.book.sphinx.rebuild_document(document, node_mapping) assert normalize(document.pformat()) == normalize(""" <document source="test"> <literal_block xml:space="preserve"> >>> string = 'Hello, world!' <literal_block xml:space="preserve"> >>> for i in range(3): ... string += " {}".format(i) ... <literal_block xml:space="preserve"> >>> print(string) Hello, world! 0 1 2 """)
def test_shared_resources(): server_a, server_b = Server(), Server() server_a.boot(maximum_logins=2) server_b.connect() with supriya.SynthDefBuilder(frequency=440) as builder: _ = supriya.ugens.Out.ar( bus=0, source=supriya.ugens.SinOsc.ar(frequency=builder["frequency"]) ) synthdef = builder.build(name="foo") synth = supriya.Synth(synthdef=synthdef) transcript_a = server_a.osc_io.capture() transcript_b = server_b.osc_io.capture() with transcript_a, transcript_b: synth.allocate(target_node=server_b) assert synth not in server_a assert synth in server_b assert [(label, osc_message) for _, label, osc_message, _ in transcript_a] == [ ("R", OscMessage("/n_go", 67109864, 2, -1, -1, 0)) ] assert [(label, osc_message) for _, label, osc_message, _ in transcript_b] == [ ("S", OscMessage(5, synthdef.compile(), OscMessage(9, "foo", 67109864, 0, 2))), ("R", OscMessage("/n_go", 67109864, 2, -1, -1, 0)), ("R", OscMessage("/done", "/d_recv")), ] # TODO: Server A doesn't actually know what this SynthDef should be. assert str(server_a.query_local_nodes(True)) == normalize( """ NODE TREE 0 group 1 group 2 group 67109864 default amplitude: 0.1, frequency: 440.0, gate: 1.0, out: 0.0, pan: 0.5 """ ) assert str(server_b.query_local_nodes(True)) == normalize( """ NODE TREE 0 group 1 group 2 group 67109864 foo frequency: 440.0 """ )
def test_system_link_audio_1(): assert normalize(str(system_link_audio_1)) == normalize( """ synthdef: name: system_link_audio_1 ugens: - Control.kr: null - BinaryOpUGen(LESS_THAN_OR_EQUAL).kr: left: Control.kr[1:fade_time] right: 0.0 - EnvGen.kr: done_action: Control.kr[0:done_action] envelope[0]: BinaryOpUGen(LESS_THAN_OR_EQUAL).kr[0] envelope[10]: 5.0 envelope[11]: -3.0 envelope[1]: 2.0 envelope[2]: 1.0 envelope[3]: -99.0 envelope[4]: 1.0 envelope[5]: 1.0 envelope[6]: 5.0 envelope[7]: 3.0 envelope[8]: 0.0 envelope[9]: 1.0 gate: Control.kr[2:gate] level_bias: 0.0 level_scale: 1.0 time_scale: Control.kr[1:fade_time] - InFeedback.ar: bus: Control.kr[3:in_] - BinaryOpUGen(MULTIPLICATION).ar: left: InFeedback.ar[0] right: EnvGen.kr[0] - Out.ar: bus: Control.kr[4:out] source[0]: BinaryOpUGen(MULTIPLICATION).ar[0] """ ) sc_compiled = SuperColliderSynthDef( "system_link_audio_1", r""" | out=0, in=16, vol=1, level=1, lag=0.05, doneAction=2 | var env = EnvGate(i_level: 0, doneAction:doneAction, curve:'sin') * Lag.kr(vol * level, lag); Out.ar(out, InFeedback.ar(in, 1) * env) """, r"[\kr, \kr, \kr, \kr, \kr, \ir]", ).compile() sc_synthdef = SynthDefDecompiler.decompile_synthdef(sc_compiled) assert normalize(str(sc_synthdef)) == normalize( """ synthdef: name: system_link_audio_1 ugens: - Control.ir: null - Control.kr: null - BinaryOpUGen(MULTIPLICATION).kr/0: left: Control.kr[2:vol] right: Control.kr[3:level] - Lag.kr: lag_time: Control.kr[4:lag] source: BinaryOpUGen(MULTIPLICATION).kr/0[0] - InFeedback.ar: bus: Control.kr[1:in] - Control.kr: null - Control.kr: null - EnvGen.kr: done_action: Control.ir[0:doneAction] envelope[0]: 0.0 envelope[10]: 3.0 envelope[11]: 0.0 envelope[1]: 2.0 envelope[2]: 1.0 envelope[3]: -99.0 envelope[4]: 1.0 envelope[5]: 1.0 envelope[6]: 3.0 envelope[7]: 0.0 envelope[8]: 0.0 envelope[9]: 1.0 gate: Control.kr[0:gate] level_bias: 0.0 level_scale: 1.0 time_scale: Control.kr[0:fadeTime] - BinaryOpUGen(MULTIPLICATION).kr/1: left: EnvGen.kr[0] right: Lag.kr[0] - BinaryOpUGen(MULTIPLICATION).ar: left: InFeedback.ar[0] right: BinaryOpUGen(MULTIPLICATION).kr/1[0] - Out.ar: bus: Control.kr[0:out] source[0]: BinaryOpUGen(MULTIPLICATION).ar[0] """ ) py_compiled = system_link_audio_1.compile() assert py_compiled == ( b"SCgf\x00\x00\x00\x02\x00\x01\x13system_link_audio_1\x00\x00\x00\x07\x00\x00" b"\x00\x00?\x80\x00\x00@\x00\x00\x00\xc2\xc6\x00\x00@\xa0\x00\x00@@" b"\x00\x00\xc0@\x00\x00\x00\x00\x00\x05@\x00\x00\x00<\xa3\xd7\n?\x80" b"\x00\x00A\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x05\x0bdone_action\x00\x00" b"\x00\x00\tfade_time\x00\x00\x00\x01\x04gate\x00\x00\x00\x02\x03in" b"_\x00\x00\x00\x03\x03out\x00\x00\x00\x04\x00\x00\x00\x06\x07Contro" b"l\x01\x00\x00\x00\x00\x00\x00\x00\x05\x00\x00\x01\x01\x01\x01\x01\x0cBinary" b"OpUGen\x01\x00\x00\x00\x02\x00\x00\x00\x01\x00\n\x00\x00\x00\x00\x00\x00\x00" b"\x01\xff\xff\xff\xff\x00\x00\x00\x00\x01\x06EnvGen\x01\x00\x00" b"\x00\x11\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02" b"\xff\xff\xff\xff\x00\x00\x00\x01\xff\xff\xff\xff\x00\x00\x00\x00" b"\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00" b"\x00\x00\x00\x01\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x02" b"\xff\xff\xff\xff\x00\x00\x00\x01\xff\xff\xff\xff\x00\x00\x00\x03" b"\xff\xff\xff\xff\x00\x00\x00\x01\xff\xff\xff\xff\x00\x00\x00\x01" b"\xff\xff\xff\xff\x00\x00\x00\x04\xff\xff\xff\xff\x00\x00\x00\x05" b"\xff\xff\xff\xff\x00\x00\x00\x00\xff\xff\xff\xff\x00\x00\x00\x01" b"\xff\xff\xff\xff\x00\x00\x00\x04\xff\xff\xff\xff\x00\x00\x00\x06\x01\nInFeed" b"back\x02\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00" b"\x00\x00\x03\x02\x0cBinaryOpUGen\x02\x00\x00\x00\x02\x00\x00\x00\x01\x00\x02" b"\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x02\x03Ou" b"t\x02\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" b"\x00\x00\x00\x04\x00\x00\x00\x04\x00\x00\x00\x00\x00\x00" )