Exemplo n.º 1
0
def test_get_bundle_sort_ports(data_regression: DataRegressionFixture,
                               check: bool = True) -> Component:

    lengths = {}

    c = gf.Component("test_get_bundle_sort_ports")
    ys_right = [0, 10, 20, 40, 50, 80]
    pitch = 127.0
    N = len(ys_right)
    ys_left = [(i - N / 2) * pitch for i in range(N)]

    right_ports = [
        gf.Port(f"R_{i}", (0, ys_right[i]), 0.5, 180) for i in range(N)
    ]
    left_ports = [
        gf.Port(f"L_{i}", (-400, ys_left[i]), 0.5, 0) for i in range(N)
    ]
    left_ports.reverse()
    routes = gf.routing.get_bundle(right_ports, left_ports)

    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 2
0
def test_get_bundle_udirect(
    data_regression: DataRegressionFixture, check: bool = True
) -> Component:

    c = gf.Component("test_get_bundle_udirect")

    pad = gf.partial(gf.c.pad, size=(10, 10))
    pad_south = gf.components.pad_array(orientation=270, spacing=(15.0, 0), pad=pad)
    pt = c << pad_south
    pb = c << pad_south
    pb.rotate(90)
    pt.rotate(90)
    pb.move((0, -100))

    pbports = pb.get_ports_list()
    ptports = pt.get_ports_list()

    pbports.reverse()

    routes = gf.routing.get_bundle(pbports, ptports, radius=5)

    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
def test_get_bundle_west_to_north(
    data_regression: DataRegressionFixture, check: bool = True
) -> Component:

    lengths = {}

    c = gf.Component("test_get_bundle_west_to_north")
    pad = gf.partial(gf.c.pad, size=(10, 10))
    c = gf.Component()
    pad_south = gf.components.pad_array(orientation=270, spacing=(15.0, 0.0), pad=pad)
    pad_north = gf.components.pad_array(orientation=90, spacing=(15.0, 0.0), pad=pad)
    pl = c << pad_south
    pb = c << pad_north
    pl.rotate(90)
    pb.move((100, -100))

    pbports = pb.get_ports_list()
    ptports = pl.get_ports_list()

    c.add_ports(pbports, prefix="N")
    c.add_ports(ptports, prefix="S")

    routes = gf.routing.get_bundle(
        pbports,
        ptports,
        bend=gf.components.wire_corner,
    )
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 4
0
def test_netlists(
    component_type: str,
    full_settings: bool,
    data_regression: DataRegressionFixture,
    check: bool = True,
    component_factory=factory,
) -> None:
    """Write netlists for hierarchical circuits.
    Checks that both netlists are the same
    jsondiff does a hierarchical diff

    Component -> netlist -> Component -> netlist
    """
    c = component_factory[component_type]()
    n = c.get_netlist(full_settings=full_settings)
    if check:
        data_regression.check(OmegaConf.to_container(n))

    yaml_str = OmegaConf.to_yaml(n, sort_keys=True)
    # print(yaml_str)
    c2 = gf.read.from_yaml(yaml_str, component_factory=component_factory)
    n2 = c2.get_netlist(full_settings=full_settings)

    d = jsondiff.diff(n, n2)
    # print(yaml_str)
    # print(d)
    # yaml_str2 = OmegaConf.to_yaml(n2, sort_keys=True)
    # print(yaml_str2)
    assert len(d) == 0, d
Exemplo n.º 5
0
 def _check_agent_state(self, state: Dict[str, Any],
                        data_regression: DataRegressionFixture):
     """
     Given an agent state, test that it is as expected.
     """
     del state['times']  # Delete variable timestamps
     data_regression.check(state)
Exemplo n.º 6
0
def test_prompt(capsys, monkeypatch, data_regression: DataRegressionFixture):

	inputs = iter([
			'',
			'',
			'',
			'',
			"24",
			"Bond007",
			"badpassword",
			"baspassword",
			"badpassword",
			"badpassword",
			"badpassword",
			"badpassword",
			])

	def fake_input(prompt):
		value = next(inputs)
		print(f"{prompt}{value}".rstrip())
		return value

	monkeypatch.setattr(click.termui, "visible_prompt_func", fake_input)

	assert prompt(text="What is your age", prompt_suffix="? ", type=click.INT) == 24

	assert prompt(text="Username", type=click.STRING) == "Bond007"
	assert prompt(text="Password", type=click.STRING, confirmation_prompt=True) == "badpassword"
	assert prompt(
			text="Password",
			type=click.STRING,
			confirmation_prompt="Are you sure about that? ",
			) == "badpassword"

	data_regression.check(list(StringList(capsys.readouterr().out.splitlines())))
Exemplo n.º 7
0
def test_facing_ports(
    data_regression: DataRegressionFixture,
    check: bool = True,
):

    dy = 200.0
    xs1 = [-500, -300, -100, -90, -80, -55, -35, 200, 210, 240, 500, 650]

    pitch = 10.0
    N = len(xs1)
    xs2 = [-20 + i * pitch for i in range(N // 2)]
    xs2 += [400 + i * pitch for i in range(N // 2)]

    a1 = 90
    a2 = a1 + 180

    ports1 = [Port(f"top_{i}", (xs1[i], 0), 0.5, a1) for i in range(N)]
    ports2 = [Port(f"bottom_{i}", (xs2[i], dy), 0.5, a2) for i in range(N)]

    c = gf.Component("test_facing_ports")
    routes = get_bundle(ports1, ports2)
    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
        difftest(c)

    return c
def test_get_bundle_west_to_north2(
    data_regression: DataRegressionFixture, check: bool = True
) -> Component:

    lengths = {}
    c = gf.Component("test_get_bundle_west_to_north2")
    pbottom_facing_north = gf.port.port_array(
        midpoint=(0, 0), orientation=90, pitch=(30, 0)
    )
    ptop_facing_west = gf.port.port_array(
        midpoint=(100, 100), orientation=180, pitch=(0, -30)
    )

    routes = gf.routing.get_bundle(
        pbottom_facing_north,
        ptop_facing_west,
        bend=gf.components.wire_corner,
    )

    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 9
0
def test_via_Repo_class(
    temp_repo,
    capsys,
    file_regression: FileRegressionFixture,
    data_regression: DataRegressionFixture,
    monkeypatch,
    example_config,
):

    with in_directory(temp_repo.path):
        (temp_repo.path / "repo_helper.yml").write_text(example_config)
        (temp_repo.path / "requirements.txt").touch()
        (temp_repo.path / "tests").maybe_make()
        (temp_repo.path / "tests" / "requirements.txt").touch()
        (temp_repo.path / "README.rst").touch()
        (temp_repo.path / "doc-source").mkdir()
        (temp_repo.path / "doc-source" / "index.rst").touch()
        (temp_repo.path / ".pre-commit-config.yaml").touch()

        rh = RepoHelper(temp_repo.path)
        rh.load_settings()
        managed_files = rh.run()

    data_regression.check(sorted(managed_files))

    assert capsys.readouterr().out == ''
    assert capsys.readouterr().err == ''
Exemplo n.º 10
0
def test_netlists(
    yaml_key: str,
    full_settings: bool,
    data_regression: DataRegressionFixture,
    check: bool = True,
) -> None:
    """Write netlists for hierarchical circuits.
    Checks that both netlists are the same
    jsondiff does a hierarchical diff

    Component -> netlist -> Component -> netlist
    """
    yaml_string = yaml_strings[yaml_key]
    c = from_yaml(yaml_string)
    n = c.get_netlist(full_settings=full_settings)
    if check:
        data_regression.check(OmegaConf.to_container(n))

    yaml_str = OmegaConf.to_yaml(n, sort_keys=True)
    # print(yaml_str)
    c2 = from_yaml(yaml_str)
    n2 = c2.get_netlist(full_settings=full_settings)
    d = jsondiff.diff(n, n2)
    assert len(d) == 0, print(d)
    return c2
Exemplo n.º 11
0
def test_link_optical_ports_no_grouping(data_regression: DataRegressionFixture,
                                        check: bool = True) -> Component:

    c = gf.Component("test_link_optical_ports_no_grouping")
    w = c << gf.components.straight_array(n=4, spacing=200)
    d = c << gf.components.nxn(west=4, east=1)
    d.y = w.y
    d.xmin = w.xmax + 200

    ports1 = [
        w.ports["o7"],
        w.ports["o8"],
    ]
    ports2 = [
        d.ports["o2"],
        d.ports["o1"],
    ]

    routes = get_bundle_same_axis_no_grouping(ports1, ports2, sort_ports=True)
    # routes = gf.routing.get_bundle(ports1, ports2, sort_ports=True)

    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 12
0
def test_components(yaml_index: int,
                    data_regression: DataRegressionFixture,
                    check: bool = True) -> None:
    yaml = yaml_list[yaml_index]
    c = gf.read.from_yaml(yaml)
    difftest(c)
    if check:
        data_regression.check(c.to_dict())
Exemplo n.º 13
0
def test_scan_list(data, data_regression: DataRegressionFixture, scan_no):
    # Workaround for https://github.com/ESSS/pytest-regressions/issues/26
    scan = data.scan_list[scan_no]
    data_regression.check({
        "intensity_list":
        list(map(float, scan.intensity_list)),
        "mass_list":
        list(map(float, scan.mass_list)),
    })
Exemplo n.º 14
0
def test_write_wheel(builder,
                     advanced_file_regression: AdvancedFileRegressionFixture,
                     data_regression: DataRegressionFixture):
    builder.write_wheel()
    advanced_file_regression.check_file(builder.dist_info / "WHEEL")
    # Check the file can be read by EmailMessage
    with (builder.dist_info / "WHEEL").open() as fp:
        data = message_from_file(fp)
    data_regression.check(dict(data))
Exemplo n.º 15
0
def test_settings(yaml_key: str,
                  data_regression: DataRegressionFixture,
                  check: bool = True) -> Component:
    """Avoid regressions when exporting settings."""
    yaml_string = yaml_strings[yaml_key]
    c = from_yaml(yaml_string)

    if check:
        data_regression.check(c.to_dict())
    return c
Exemplo n.º 16
0
 def test_y_data(self, tic, data_regression: DataRegressionFixture):
     assert tic.y_data[:10] == [
         134909300.0,
         135957800.0,
         131716500.0,
         130281100.0,
         129322300.0,
         127338400.0,
         126183900.0,
         123384600.0,
         121993400.0,
         118873000.0,
     ]
     data_regression.check({"y_data": tic.y_data})
Exemplo n.º 17
0
 def test_x_data(self, tic, data_regression: DataRegressionFixture):
     assert tic.x_data[:10] == [
         0.047216666666666664,
         0.05843333333333333,
         0.06966666666666667,
         0.08088333333333333,
         0.09211666666666667,
         0.10333333333333333,
         0.11456666666666666,
         0.12578333333333333,
         0.137,
         0.14823333333333333,
     ]
     data_regression.check({"x_data": tic.x_data})
Exemplo n.º 18
0
def test_get_bundle_u_indirect(data_regression: DataRegressionFixture,
                               angle,
                               check: bool = True,
                               dy=-200):

    xs1 = [-100, -90, -80, -55, -35] + [200, 210, 240]

    axis = "X" if angle in [0, 180] else "Y"

    pitch = 10.0
    N = len(xs1)
    xs2 = [50 + i * pitch for i in range(N)]

    a1 = angle
    a2 = a1 + 180

    if axis == "X":
        ports1 = [
            Port("top_{}".format(i), (0, xs1[i]), 0.5, a1) for i in range(N)
        ]

        ports2 = [
            Port("bottom_{}".format(i), (dy, xs2[i]), 0.5, a2)
            for i in range(N)
        ]

    else:
        ports1 = [
            Port("top_{}".format(i), (xs1[i], 0), 0.5, a1) for i in range(N)
        ]

        ports2 = [
            Port("bottom_{}".format(i), (xs2[i], dy), 0.5, a2)
            for i in range(N)
        ]

    c = gf.Component(f"test_get_bundle_u_indirect_{angle}_{dy}")

    routes = get_bundle(ports1, ports2, bend=gf.components.bend_circular)
    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
        difftest(c)

    return c
Exemplo n.º 19
0
def test_make_schema(data_regression: DataRegressionFixture):
    data_regression.check(
        make_schema(
            author,
            email,
            username,
            modname,
            copyright_years,
            repo_name,
            pypi_name,
            import_name,
            keywords,
            short_desc,
            source_dir,
            pure_python,
            stubs_package,
            on_pypi,
            enable_tests,
            enable_releases,
            enable_pre_commit,
            docker_shields,
            docker_name,
            manifest_additional,
            py_modules,
            console_scripts,
            setup_pre,
            additional_setup_args,
            platforms,
            rtfd_author,
            preserve_custom_theme,
            sphinx_html_theme,
            extra_sphinx_extensions,
            intersphinx_mapping,
            sphinx_conf_preamble,
            sphinx_conf_epilogue,
            html_theme_options,
            html_context,
            enable_docs,
            docs_dir,
            imgbot_ignore,
            mypy_deps,
            mypy_plugins,
            python_deploy_version,
            python_versions,
            tox_requirements,
            tox_build_requirements,
            tox_testenv_extras,
        ))
Exemplo n.º 20
0
    def _check_losses(
        self, opt: Opt, test_name: str, data_regression: DataRegressionFixture
    ):
        """
        Calculate and check distillation loss terms.

        Given the input opt, run eval and check each of the loss terms to make sure that
        they match what is expected.
        """
        valid, _ = testing_utils.eval_model(opt, skip_test=True)
        losses = {}
        loss_types = self.LOSS_TYPES[test_name]
        for loss_type in loss_types:
            losses[loss_type] = round_sig(valid[loss_type].value(), sig=6)
        basename = self._get_model_identifier() + '_' + test_name
        data_regression.check(losses, basename=basename)
Exemplo n.º 21
0
def test_confirm(capsys, monkeypatch, data_regression: DataRegressionFixture):

	inputs = iter(['Y', 'N', '', ''])

	def fake_input(prompt):
		value = next(inputs)
		print(f"{prompt}{value}".rstrip())
		return value

	monkeypatch.setattr(click.termui, "visible_prompt_func", fake_input)

	assert confirm(text="Do you wish to delete all files in '/' ?", default=False) is True
	assert confirm(text="Do you wish to delete all files in '/' ?", default=False) is False
	assert confirm(text="Do you wish to delete all files in '/' ?", default=False) is False
	assert confirm(text="Do you wish to delete all files in '/' ?", default=True) is True

	data_regression.check(list(StringList(capsys.readouterr().out.splitlines())))
def test_get_bundle_u_direct_different_x(
        data_regression: DataRegressionFixture,
        check: bool = True) -> Component:
    """

    .. code::

       4----5
                    ________
       3----6     4|        |
                  3|  nxn   |
       2----7     2|        |
                  1|________|
       1----8
    """

    c = gf.Component("test_get_bundle_u_direct_different_x")
    w = c << gf.components.straight_array(n=4, spacing=200)
    d = c << gf.components.nxn(west=4, east=0, north=0, south=0)
    d.y = w.y
    d.xmin = w.xmax + 200

    ports1 = w.get_ports_list(orientation=0)
    ports2 = d.get_ports_list(orientation=0)

    ports1 = [
        w.ports["o7"],
        w.ports["o8"],
    ]
    ports2 = [
        d.ports["o2"],
        d.ports["o1"],
    ]

    routes = gf.routing.get_bundle(ports1, ports2)

    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
def test_get_bundle_from_waypointsB(
    data_regression: DataRegressionFixture,
    check: bool = True,
) -> Component:

    ys1 = np.array([0, 5, 10, 15, 30, 40, 50, 60]) + 0.0
    ys2 = np.array([0, 10, 20, 30, 70, 90, 110, 120]) + 500.0
    N = ys1.size

    ports1 = [
        Port(name=f"A_{i}", midpoint=(0, ys1[i]), width=0.5, orientation=0)
        for i in range(N)
    ]
    ports2 = [
        Port(
            name=f"B_{i}",
            midpoint=(500, ys2[i]),
            width=0.5,
            orientation=180,
        ) for i in range(N)
    ]

    p0 = ports1[0].position

    c = gf.Component("B")
    c.add_ports(ports1)
    c.add_ports(ports2)
    waypoints = [
        p0 + (200, 0),
        p0 + (200, -200),
        p0 + (400, -200),
        (p0[0] + 400, ports2[0].y),
    ]

    routes = get_bundle_from_waypoints(ports1, ports2, waypoints)
    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 24
0
def test_read_sparameters(component_type: str,
                          data_regression: DataRegressionFixture,
                          check: bool = True) -> None:
    c = factory[component_type]()
    sp = sim.read_sparameters_lumerical(component=c)

    port_names = sp[0]
    f = list(sp[1])
    s = sp[2]

    lenf = s.shape[0]
    rows = s.shape[1]
    cols = s.shape[2]

    assert rows == cols == len(c.ports)
    assert len(port_names) == len(c.ports)
    if check:
        data_regression.check(dict(port_names=port_names))
    assert lenf == len(f)
Exemplo n.º 25
0
def test_actions_manager_python_versions(
    python_versions: List[str],
    data_regression: DataRegressionFixture,
):

    py_versions = {k: {"experimental": True} for k in python_versions}

    class FakeActionsManager:

        templates = SimpleNamespace()
        templates.globals = {
            "python_versions": py_versions,
            "tox_py_versions": get_tox_python_versions(python_versions),
            "third_party_version_matrix": {},
        }

        get_gh_actions_python_versions = ActionsManager.get_gh_actions_python_versions
        get_gh_actions_matrix = ActionsManager.get_gh_actions_matrix

    data_regression.check(
        FakeActionsManager().get_gh_actions_python_versions())  # type: ignore
Exemplo n.º 26
0
def test_suggest_classifiers_stage(tmp_pathplus, data_regression: DataRegressionFixture, stage):
	(tmp_pathplus / "repo_helper.yml").write_lines([
			"modname: repo_helper",
			'copyright_years: "2020"',
			'author: "Dominic Davis-Foster"',
			'email: "*****@*****.**"',
			'version: "0.0.1"',
			'username: "******"',
			"license: 'LGPLv3+'",
			"short_desc: 'Update multiple configuration files, build scripts etc. from a single location.'",
			])

	(tmp_pathplus / "requirements.txt").touch()
	(tmp_pathplus / "repo_helper").mkdir()

	with in_directory(tmp_pathplus):
		runner = CliRunner()
		result: Result = runner.invoke(suggest.classifiers, catch_exceptions=False, args=["-s", stage, "-l"])
		assert result.exit_code == 0

	classifiers = result.stdout.splitlines()
	data_regression.check(classifiers)
Exemplo n.º 27
0
def test_get_bundle_optical2(data_regression: DataRegressionFixture,
                             check: bool = True) -> Component:

    lengths = {}

    c = gf.Component("test_get_bundle_optical2")
    w = c << gf.components.straight_array(n=4, spacing=200)
    d = c << gf.components.nxn(west=4, east=1)
    d.y = w.y
    d.xmin = w.xmax + 200

    ports1 = w.get_ports_list(orientation=0)
    ports2 = d.get_ports_list(orientation=180)

    routes = gf.routing.get_bundle(ports1, ports2, sort_ports=True)

    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 28
0
def test_get_bundle_electrical(
    data_regression: DataRegressionFixture, check: bool = True
) -> Component:

    lengths = {}

    c = gf.Component("test_get_bundle")
    c1 = c << gf.components.pad()
    c2 = c << gf.components.pad()
    c2.move((200, 100))

    routes = gf.routing.get_bundle(
        [c1.ports["e3"]],
        [c2.ports["e1"]],
        bend=gf.components.wire_corner,
        width=10,
        # auto_widen=False,
        auto_widen=True,
    )
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    routes = gf.routing.get_bundle(
        [c1.ports["e4"]],
        [c2.ports["e3"]],
        start_straight_length=20.0,
        bend=gf.components.wire_corner,
        width=10,
    )
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
    return c
Exemplo n.º 29
0
def test_get_bundle_udirect(data_regression: DataRegressionFixture,
                            check: bool = True,
                            dy=200,
                            angle=270):
    xs1 = [-100, -90, -80, -55, -35, 24, 0] + [200, 210, 240]
    axis = "X" if angle in [0, 180] else "Y"

    pitch = 10.0
    N = len(xs1)
    xs2 = [70 + i * pitch for i in range(N)]

    if axis == "X":
        ports1 = [Port(f"top_{i}", (0, xs1[i]), 0.5, angle) for i in range(N)]

        ports2 = [
            Port(f"bottom_{i}", (dy, xs2[i]), 0.5, angle) for i in range(N)
        ]

    else:
        ports1 = [Port(f"top_{i}", (xs1[i], 0), 0.5, angle) for i in range(N)]

        ports2 = [
            Port(f"bottom_{i}", (xs2[i], dy), 0.5, angle) for i in range(N)
        ]

    c = gf.Component(name="test_get_bundle_udirect")
    routes = get_bundle(ports1, ports2, bend=gf.components.bend_circular)
    lengths = {}
    for i, route in enumerate(routes):
        c.add(route.references)
        lengths[i] = route.length

    if check:
        data_regression.check(lengths)
        difftest(c)

    return c
Exemplo n.º 30
0
    def _regression(self, data_regression: DataRegressionFixture,
                    datatype: str):
        import random
        from parlai.core.worlds import create_task
        from parlai.core.params import ParlaiParser

        basename = f"{self.task}_{datatype}".replace(":", "_")

        if self.stream:
            datatype = datatype + ':stream'
        if datatype == 'train:stream':
            datatype = datatype + ':ordered'

        random.seed(42)

        opt = ParlaiParser(True, True).parse_kwargs(
            model='fixed_response',
            fixed_response='none',
            task=self.task,
            datatype=datatype,
            batchsize=1,
        )

        world = create_task(opt, [])
        acts = []
        for _ in range(5):
            world.parley()
            act = self._safe(world.get_acts())
            acts.append(act)

        teacher = world.get_task_agent()
        output = {
            'acts': acts,
            'num_episodes': teacher.num_episodes(),
            'num_examples': teacher.num_examples(),
        }
        data_regression.check(output, basename=basename)