Пример #1
0
def test_invalid_toml_files(toml_file):
    if toml_file.stem in INVALID_EXCLUDE_FILE:
        pytest.skip()
    with pytest.raises(RuntimeError):
        with open(str(toml_file), "r") as f:
            toml_file_string = f.read()
            pytomlpp.loads(toml_file_string)
Пример #2
0
def test_round_trip_for_valid_toml_files(toml_file):
    with open(str(toml_file), "r") as f:
        text = f.read()
    print(text.strip(), end="\n\n")
    table = pytomlpp.loads(text)
    print(table, end="\n\n")

    text2 = pytomlpp.dumps(table)
    print(text2, end="\n\n")
    table2 = pytomlpp.loads(text2)
    assert table == table2
Пример #3
0
 def load(source: Path, missing_ok: bool = False) -> Dict:
     try:
         return toml.loads(source.read_text())
     except FileNotFoundError as err:
         if missing_ok:
             return {}
         else:
             raise err from None
Пример #4
0
def test_valid_toml_files(toml_file):
    if toml_file.stem in VALID_EXCLUDE_FILE:
        pytest.skip()
    with open(str(toml_file), "r") as f:
        toml_file_string = f.read()
        table = pytomlpp.loads(toml_file_string)
        table_json = json.loads(toml_file.with_suffix(".json").read_text())
        assert_matches_json(table, table_json)
Пример #5
0
def run(run_count = 5000):
    test_data = ''
    with open('data.toml', 'r', encoding='utf-8') as f:
        test_data = f.read()
    print(f'Parsing data.toml {run_count} times:')
    baseline = benchmark('pytomlpp', run_count, lambda: pytomlpp.loads(test_data))
    benchmark('tomli', run_count, lambda: tomli.loads(test_data), compare_to=baseline)
    benchmark('toml', run_count, lambda: toml.loads(test_data), compare_to=baseline)
    benchmark('qtoml', run_count, lambda: qtoml.loads(test_data), compare_to=baseline)
    benchmark('tomlkit', run_count, lambda: tomlkit.parse(test_data), compare_to=baseline)
Пример #6
0
def readTotalOccurences():
    with open(path + "/~temp-powersearch-config.toml", "r") as file:
        try:
            current_occurences = "DEFAULT_VALUE"
            while current_occurences == "DEFAULT_VALUE":
                settings_file_content = file.read()
                settings_dict = dict(pytomlpp.loads(settings_file_content))
                current_occurences = settings_dict.get("total_occurences",
                                                       "DEFAULT_VALUE")
            return current_occurences
        except Exception as e:
            print("ERROR: Failed to read ~temp-powersearch-config.toml")
Пример #7
0
def read_toml(filename):
    if os.path.isfile(filename) is False:
        print('yaml file does not exist: ' + filename)
    else:
        with open(filename) as filedata:
            try:
                data = filedata.read()
                d = toml.loads(data)
                return (d)
            except Exception as e:
                print('toml decode error: ' + str(filename))
                raise (e)
    return None
    async def check_toml(self, key):
        '''
        Attempt to retrieve and parse a TOML file for a domain provided through a manifest query.

        :param dict key: Validation public key, domain, and other info
        '''
        url = "https://" + key['domain'] + "/.well-known/xrp-ledger.toml"
        validators = []
        #logging.info(f"Preparing to retrieve TOML for: {key['domain']}.")
        try:
            response_content = await self.http_request(url)
            validators = pytomlpp.loads(str(response_content))['VALIDATORS']
            for i in validators:
                if i['public_key'] == key['key']:
                    try:
                        key['toml_verified'] = True
                        key['network'] = i['network'].lower()
                        key['owner_country'] = i['owner_country'].lower()
                        key['server_country'] = i['server_country'].lower()
                        #logging.info(f"Successfully retrieved and parsed the TOML for: {key['domain']}.")
                    except (KeyError) as error:
                        logging.info(
                            f"TOML file for: {key['domain']} was missing one or more keys: {error}."
                        )
                        continue
                else:
                    # To-do: Check to see if novel keys are listed in the TOML.
                    # Then use the manifest verify their domains.
                    logging.info(
                        f"An additional validator key was detected while querying {key['domain']}."
                    )
        except (pytomlpp._impl.DecodeError, ) as error:
            logging.info(
                f"Unable to decode the TOML for: {key['domain']}. Error: {error}."
            )

        return key
Пример #9
0
import quicclient

APP_NAME = "QUICProxy"
APP_AUTHOR = "iv-org"

CONFIG_DIRECTORY = pathlib.Path(
    f"{appdirs.user_config_dir(APP_NAME, APP_AUTHOR)}")
CONFIG_DIRECTORY.mkdir(parents=True, exist_ok=True)

CONFIG_FILE = pathlib.Path(
    f"{appdirs.user_config_dir(APP_NAME, APP_AUTHOR)}/config.toml")
CONFIG_FILE.touch(exist_ok=True)

with open(f"{CONFIG_FILE}") as config:
    config = pytomlpp.loads(config.read())
if not config:
    config = {"listen": "0.0.0.0:7192", "open_connections": 5}
routes = web.RouteTableDef()


def process_cli_args():
    # Taken from https://stackoverflow.com/a/20663028
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '-d',
        '--debug',
        help="Print lots of debugging statements",
        action="store_const",
        dest="loglevel",
        const=logging.DEBUG,
Пример #10
0
def test_keys():
    toml_string = "a = 3"
    table = pytomlpp.loads(toml_string)
    keys = table.keys()
    assert len(keys) == 1
    assert list(keys)[0] == "a"
Пример #11
0
 def loads(self, s):
     new_obj = TomlSerializer.unpack_raw_object(toml.loads(s))
     TomlSerializer.restore_none_values(new_obj)
     return restore_object(new_obj)
Пример #12
0
 def loads(self, s):
     return deserialize(pytomlpp.loads(s))
Пример #13
0
import pytomlpp
import toml
import tomlkit
import qtoml
import timeit

def benchmark(name, func, number=5000):
    print(f'{name:>10}: Running...', end='', flush=True)
    res = str(timeit.timeit(func, number=number)).split('.')
    print('\b'*10 + f'{res[0]:>3}.{res[1]} s')

test_data = ''
with open('data.toml', 'r', encoding='utf-8') as f:
    test_data = f.read()

benchmark('pytomlpp', lambda: pytomlpp.loads(test_data))
benchmark('toml', lambda: toml.loads(test_data))
benchmark('qtoml', lambda: qtoml.loads(test_data))
benchmark('tomlkit', lambda: tomlkit.parse(test_data))
Пример #14
0
import pytomlpp

with open('example.toml', mode='r', encoding='utf-8') as f:
    text = f.read()

# print(text)

# ここに Toml の処理を書く
print("Tomlの読込")
doc = pytomlpp.loads(text)

print(f"ip は {doc['servers']['alpha']['ip']}")

# pytomlpp.dumps({"你好": "world"})
Пример #15
0
 def loads(src):
     packed = pytomlpp.loads(src)
     return deconvert(packed)
Пример #16
0
 def default_template():
     return toml.loads(resources.read_text(defaults, "template.toml"))
Пример #17
0
    def loads(self, data: str) -> dict or list:

        return from_dict(pytomlpp.loads(data))
Пример #18
0
def loads(s):
    result = toml.loads(s)
    replace_values(result, NULL_STRING, None)
    return result
Пример #19
0
 def default_config():
     return toml.loads(resources.read_text(defaults, "config.toml"))