Esempio n. 1
0
def test_encode_unencodable():
    def func():
        pass
    # functions cannot be encoded
    value = { 'a': func }
    with pytest.raises(qtoml.encoder.TOMLEncodeError):
        qtoml.dumps(value)
Esempio n. 2
0
def test_encode_none():
    value = { 'a': None }
    with pytest.raises(qtoml.encoder.TOMLEncodeError):
        qtoml.dumps(value)
    rv = qtoml.dumps(value, encode_none=0)
    cycle = qtoml.loads(rv)
    assert cycle['a'] == 0
Esempio n. 3
0
def test_non_str_keys():
    value = {1: 'foo'}
    with pytest.raises(qtoml.TOMLEncodeError):
        qtoml.dumps(value)

    class EnsureStringKeys(qtoml.TOMLEncoder):
        def default(self, o):
            if isinstance(o, dict):
                return {str(k): v for k, v in o.items()}
            return super().default(o)

    v = EnsureStringKeys().encode(value)
    assert qtoml.loads(v) == {'1': 'foo'}
Esempio n. 4
0
def generate_config():
    # TODO ensure this works still
    config = qtoml.loads(Path("example.toml").read_text())
    botsettings = config["Bot"]
    for each in botsettings.keys():
        if type(botsettings[each]) is bool:
            botsettings[each] = prompt(
                f"Would you like to enable {each}? y/N ")
        elif type(botsettings[each]) is int:
            numerical_option = input(f"Please enter a number for {each}: ")
            assert numerical_option.isdigit() is True, "Must be a number!"
            botsettings[each] = int(numerical_option)
        else:
            botsettings[each] = input(f"Please enter your {each}: ")
    modules = getmodules()
    print(
        "Enter the number for each module you'd like to enable, separated by commas"
    )
    print("Example: 1,5,8")
    message = ", ".join([f"{i}) {v}" for i, v in enumerate(modules)])
    to_enable = input(f"{message}\n")
    for module_index in to_enable.split(","):
        if module_index.isdigit() and int(module_index) <= len(modules):
            config["Modules"]["enabled"].append(modules[int(module_index)])
    return qtoml.dumps(config)
Esempio n. 5
0
def test_encode_default():
    value = UserDict({'a': 10, 'b': 20})
    with pytest.raises(qtoml.TOMLEncodeError):
        qtoml.dumps(value)

    class UserDictEncoder(qtoml.TOMLEncoder):
        def default(self, obj):
            if isinstance(obj, UserDict):
                return obj.data
            # this calls the parent version which just always TypeErrors
            return super().default(obj)

    v = UserDictEncoder().encode(value)
    v2 = qtoml.dumps(value, cls=UserDictEncoder)
    assert v == v2
    nv = qtoml.loads(v)
    assert nv == value.data
Esempio n. 6
0
def test_encode_path():
    class PathEncoder(qtoml.TOMLEncoder):
        def default(self, obj):
            if isinstance(obj, Path):
                return obj.as_posix()
            return super().default(obj)

    pval = {'top': {'path': Path("foo") / "bar"}}
    sval = {'top': {'path': "foo/bar"}}
    v = PathEncoder().encode(pval)
    v2 = qtoml.dumps(pval, cls=PathEncoder)
    assert v == v2
    nv = qtoml.loads(v)
    assert nv == {'top': {'path': 'foo/bar'}}

    v3 = qtoml.dumps(sval, cls=PathEncoder)
    assert v == v3
Esempio n. 7
0
def test_encode_subclass():
    value = OrderedDict(a=1, b=2, c=3, d=4, e=5)
    toml_val = qtoml.dumps(value)
    # ensure order is preserved
    assert toml_val == 'a = 1\nb = 2\nc = 3\nd = 4\ne = 5\n'
    cycle = qtoml.loads(toml_val)
    # cycle value is a plain dictionary, so this comparison is
    # order-insensitive
    assert value == cycle
Esempio n. 8
0
 def dump(self, filename):
     config = deepcopy(self.config)
     if config.get("git", {}).get("diff", None) is not None:
         diff_filename = Path(filename).parent / "diff.patch"
         with open(diff_filename, 'w') as diff_file:
             diff_file.write(config["git"]["diff"])
         config["git"]["diff"] = str(diff_filename.resolve())
     with open(filename, 'w') as config_file:
         config_file.write(toml.dumps(config))
Esempio n. 9
0
 async def download_chat(self) -> None:
     sid = self.id_from_url(self.url)
     r = await asks.post(self.chat_pages_url, data={'r': sid})
     comment_count = r.json()['count']
     r = await asks.post(self.chat_page_url,
                         data={
                             'r': sid,
                             'lastCT': int(time.time() * 1000),
                             'firstCT': 0,
                             'cpr': 1,
                             'page': 1
                         })
     o = r.json()
     # print(comment_count, o)
     d = {}
     for i in o:
         d[i['_id']] = i
     print(qtoml.dumps(d))
Esempio n. 10
0
def test_string_encode(data):
    obj = {'key': data}
    assert qtoml.loads(qtoml.dumps(obj)) == obj
Esempio n. 11
0
def test_circular_encode(data):
    assert patch_floats(qtoml.loads(qtoml.dumps(data))) == patch_floats(data)
Esempio n. 12
0
def test_invalid_encode(invalid_encode_case):
    json_val = untag(json.loads(invalid_encode_case['json']))
    with pytest.raises(qtoml.encoder.TOMLEncodeError):
        qtoml.dumps(json_val)
Esempio n. 13
0
def test_valid_encode(valid_case):
    json_val = untag(json.loads(valid_case['json']))
    toml_str = qtoml.dumps(json_val)
    toml_reload = qtoml.loads(toml_str)
    assert patch_floats(toml_reload) == patch_floats(json_val)
Esempio n. 14
0
    if args.cbor:
        cbor = cbor.dumps(data)
        print(cbor)
    if args.prettyjson:
        json = json.dumps(data, indent=2, sort_keys=True)
        print(json)
    if args.xml:
        xml = dicttoxml.dicttoxml(data, attr_type=False, custom_root='pgdl')
        print(xml.decode("utf-8"))
    if args.prettyxml:
        xml = dicttoxml.dicttoxml(data, attr_type=False, custom_root='pgdl')
        x = xml.decode("utf-8")
        dom = parseString(x)
        print(dom.toprettyxml())
    if args.toml:
        toml = qtoml.dumps(data)
        print(toml)
    if args.yaml:
        print(yaml.dump(data))
    if args.pgdl:
        print(raw)
    if args.graphql:
        indentation = '  '

        def set_datatype(f):
            if f == 'string':
                return 'String'
            elif f == 'int':
                return 'Int'
            elif f == 'integer':
                return 'Int'
def save_toml(path, contents):
    toml = qtoml.dumps(contents)
    f = open(path, 'w')
    f.write(toml)
    f.close()