示例#1
0
def test_items_can_be_appended_to_and_removed_from_an_inline_table():
    string = """table = {}
"""

    parser = Parser(string)
    _, table = parser._parse_item()

    assert isinstance(table, InlineTable)
    assert "{}" == table.as_string()

    table.append(Key("foo"),
                 String(StringType.SLB, "bar", "bar", Trivia(trail="")))

    assert '{foo = "bar"}' == table.as_string()

    table.append(Key("baz"), Integer(34, Trivia(trail=""), "34"))

    assert '{foo = "bar", baz = 34}' == table.as_string()

    table.remove(Key("baz"))

    assert '{foo = "bar"}' == table.as_string()

    table.remove(Key("foo"))

    assert "{}" == table.as_string()

    with pytest.raises(NonExistentKey):
        table.remove(Key("foo"))
示例#2
0
def test_items_can_be_appended_to_and_removed_from_a_table():
    string = """[table]
"""

    parser = Parser(string)
    _, table = parser._parse_table()

    assert isinstance(table, Table)
    assert "\n" == table.as_string()

    table.append(Key("foo"),
                 String(StringType.SLB, "bar", "bar", Trivia(trail="\n")))

    assert '\nfoo = "bar"\n' == table.as_string()

    table.append(
        Key("baz"),
        Integer(34, Trivia(comment_ws="   ", comment="# Integer", trail=""),
                "34"),
    )

    assert '\nfoo = "bar"\nbaz = 34   # Integer' == table.as_string()

    table.remove(Key("baz"))

    assert '\nfoo = "bar"\n' == table.as_string()

    table.remove(Key("foo"))

    assert "\n" == table.as_string()

    with pytest.raises(NonExistentKey):
        table.remove(Key("foo"))
示例#3
0
文件: cli.py 项目: jhrmnn/deepqmc
def collect_kwarg_defaults(func, mapping):
    kwargs = tomlkit.table()
    for p in inspect.signature(func).parameters.values():
        if p.kind is inspect.Parameter.POSITIONAL_OR_KEYWORD:
            continue
        if p.name == 'kwargs':
            assert p.default is p.empty
            assert p.kind is inspect.Parameter.VAR_KEYWORD
            sub_kwargs = _get_subkwargs(func, 'kwargs', mapping)
            for item in sub_kwargs.value.body:
                kwargs.add(*item)
        elif p.name.endswith('_kwargs'):
            if mapping.get((func, p.name)) is True:
                kwargs[p.name] = p.default
            else:
                assert p.default is None
                assert p.kind is inspect.Parameter.KEYWORD_ONLY
                sub_kwargs = _get_subkwargs(func, p.name, mapping)
                kwargs[p.name] = sub_kwargs
        else:
            assert p.kind is inspect.Parameter.KEYWORD_ONLY
            if p.default is None:
                kwargs.add(Comment(Trivia(comment=f'#: {p.name} = ...')))
            else:
                try:
                    kwargs[p.name] = p.default
                except ValueError:
                    print(func, p.name, p.kind, p.default)
                    raise
    return kwargs
示例#4
0
def test_array_add_line_invalid_value():
    t = array()
    with pytest.raises(ValueError, match="is not allowed"):
        t.add_line(1, ws(" "))
    with pytest.raises(ValueError, match="is not allowed"):
        t.add_line(Comment(Trivia("  ", comment="test")))
    assert len(t) == 0
示例#5
0
def test_booleans_comparison():
    boolean = Bool(True, Trivia())

    assert boolean

    boolean = Bool(False, Trivia())

    assert not boolean

    s = """[foo]
value = false
"""

    content = parse(s)

    assert {"foo": {"value": False}} == content
    assert {"value": False} == content["foo"]
示例#6
0
def load_pipfile(p=None):
    # type: (Optional[path.Path]) -> TOMLDocument
    if p is None:
        p = path.Path(ROOT_PIPFILE)

    with open(p, "r") as fp:
        doc = loads(fp.read())
    doc._parsed = True

    sources = []
    have_default = False
    for key in ("source", "sources"):
        try:
            item = doc.item(key)  # type: Union[AoT, Table]
        except KeyError:
            continue

        doc.remove(key)

        if isinstance(item, AoT):
            items = item.body
        else:
            items = item.value

        for source in items:
            if not isinstance(source, Table):
                source = Table(source, Trivia(trail=""), is_aot_element=True)
            container = source.value
            reorder_container(container,
                              pipfile_source_key,
                              key_type=KeyType.Basic)
            if not have_default and is_default(container):
                have_default = True

            sources.append(source)

    if not have_default:
        source = Table(Container(True), Trivia(), True)
        for k, v in DEFAULT_SOURCE:
            source.append(k, v)

        sources.insert(0, source)

    doc.append("source", AoT(sources, parsed=True))
    return doc
示例#7
0
    def _migrate_dependency_groups(self, pipenv_key: str, group_name: str):
        if "group" not in self._pyproject["tool"]["poetry"]:
            self._pyproject["tool"]["poetry"]["group"] = Table(
                Container(), Trivia(), False, is_super_table=True
            )
        if group_name not in self._pyproject["tool"]["poetry"]["group"]:
            self._pyproject["tool"]["poetry"]["group"][group_name] = Table(
                Container(), Trivia(), False, is_super_table=True
            ).add("dependencies", table())

        group = self._pyproject["tool"]["poetry"]["group"][group_name]
        for name, properties in self._pipenv.get(pipenv_key, {}).items():
            name, extras = self._split_extras(name)
            if name in group["dependencies"]:
                continue
            properties = self._reformat_dependency_properties(extras, properties)
            group["dependencies"].add(name, properties)
        self._pyproject["tool"]["poetry"]["group"][group_name] = group
示例#8
0
def convert_tomlkit_buggy_types(in_value: object, parent: Item) -> Item:
    """Fix buggy items while iterating through tomlkit items

    Iterating through tomlkit items can often be buggy; this function fixes it
    """
    if isinstance(in_value, Item):
        return in_value
    if isinstance(in_value, Container):
        return Table(in_value, trivia=Trivia(), is_aot_element=False)
    return item(in_value, parent)
示例#9
0
def make_headers(dest: str, value: dict) -> Table:
    hdrs_table = table()
    hdrs_table["for"] = dest
    value_table = table().indent(2)
    for k, v in value.items():
        if "\n" in v:
            val = String(StringType.MLL, v, v, Trivia())
            value_table[k] = val
        else:
            value_table[k] = v
    hdrs_table["values"] = value_table
    return hdrs_table
示例#10
0
def test_source_to_table(source: Source, table_body: dict[str, str | bool]):
    table = Table(Container(), Trivia(), False)
    table._value = table_body

    assert source_to_table(source) == table