Пример #1
0
def test_inline_dict(encoder_cls):

	class TestDict(dict, InlineTableDict):
		pass

	t = copy.deepcopy(TEST_DICT)
	t['d'] = TestDict()
	t['d']['x'] = "abc"
	o: Dict[str, Any] = loads(dumps(t, encoder=encoder_cls))
	assert o == loads(dumps(o, encoder=encoder_cls))
Пример #2
0
def test_circular_ref():
	a = {}
	b: MutableMapping[str, Any] = {}
	b['c'] = 4
	b["self"] = b
	a['b'] = b
	with pytest.raises(ValueError, match="Circular reference detected"):
		dumps(a)

	with pytest.raises(ValueError, match="Circular reference detected"):
		dumps(b)
Пример #3
0
def test_pathlib(encoder_cls):
	o = {"root": {"path": pathlib.Path("/home/edgy")}}
	sep = "\\\\" if os.sep == '\\' else '/'
	test_str = f"""[root]
path = "{sep}home{sep}edgy"
"""
	assert test_str == dumps(o, encoder=encoder_cls)
	toml.loads(test_str)
Пример #4
0
def test_decimal():
	PLACES = Decimal(10)**-4

	d = {'a': Decimal("0.1")}
	o: Dict[str, Any] = loads(dumps(d))
	assert o == loads(dumps(o))
	assert Decimal(o['a']).quantize(PLACES) == d['a'].quantize(PLACES)

	with pytest.raises(TypeError):
		loads(2)  # type: ignore[call-overload]

	with pytest.raises(TypeError, match="expected str, bytes or os.PathLike object, not int"):
		load(2)  # type: ignore[call-overload]

	with pytest.raises(TypeError, match="expected str, bytes or os.PathLike object, not list"):
		load([])  # type: ignore[call-overload]

	with pytest.raises(
			TypeError,
			match="argument should be a str object or an os.PathLike object returning str, not <class 'bytes'>"
			):
		load(b"test.toml")  # type: ignore[call-overload]
Пример #5
0
    def dumps(
        self,
        encoder: Union[Type[toml.TomlEncoder],
                       toml.TomlEncoder] = PyProjectTomlEncoder,
    ) -> str:
        """
		Serialise to TOML.

		:param encoder: The :class:`toml.TomlEncoder` to use for constructing the output string.
		"""

        # TODO: filter out default values (lists and dicts)

        toml_dict: _PyProjectAsTomlDict = {
            "build-system": self.build_system,
            "project": self.project,
            "tool": self.tool
        }

        if toml_dict["project"] is not None:
            if "license" in toml_dict["project"] and toml_dict["project"][
                    "license"] is not None:
                toml_dict["project"] = {  # type: ignore
                    **toml_dict["project"],  # type: ignore
                    "license":
                    toml_dict["project"]["license"].to_pep621_dict()
                }

        if toml_dict["project"] is not None:
            if "readme" in toml_dict["project"] and toml_dict["project"][
                    "readme"] is not None:
                readme_dict = toml_dict["project"]["readme"].to_pep621_dict()

                if set(readme_dict.keys()) == {"file"}:
                    toml_dict["project"] = {
                        **toml_dict["project"], "readme": readme_dict["file"]
                    }  # type: ignore
                else:
                    toml_dict["project"] = {
                        **toml_dict["project"], "readme": readme_dict
                    }  # type: ignore

        return dom_toml.dumps(toml_dict, encoder)
Пример #6
0
def test_numpy_ints():
	np = pytest.importorskip("numpy")

	encoder = TomlNumpyEncoder()
	d = {'a': np.array([1, 3], dtype=np.int64)}
	o: Dict[str, Any] = loads(dumps(d, encoder=encoder))
	assert o == loads(dumps(o, encoder=encoder))

	d = {'a': np.array([1, 3], dtype=np.int32)}
	o = loads(dumps(d, encoder=encoder))
	assert o == loads(dumps(o, encoder=encoder))

	d = {'a': np.array([1, 3], dtype=np.int16)}
	o = loads(dumps(d, encoder=encoder))
	assert o == loads(dumps(o, encoder=encoder))
Пример #7
0
def test_encoder(data,
                 advanced_file_regression: AdvancedFileRegressionFixture):
    as_toml = dumps(data, encoder=TomlEncoder(dict))
    advanced_file_regression.check(as_toml, extension=".toml")
    assert toml.loads(as_toml) == data
Пример #8
0
def test_bug_196():
	d = datetime.datetime.now()
	bug_dict = {'x': d}
	round_trip_bug_dict: Dict[str, Any] = loads(dumps(bug_dict))
	assert round_trip_bug_dict == bug_dict
	assert round_trip_bug_dict['x'] == bug_dict['x']
Пример #9
0
def test_commutativity():
	o: Dict[str, Any] = loads(dumps(TEST_DICT))
	assert o == loads(dumps(o))
Пример #10
0
def test_tuple():
	d = {'a': (3, 4)}
	o: Dict[str, Any] = loads(dumps(d))
	assert o == loads(dumps(o))
Пример #11
0
def test_ordered(encoder_cls, decoder_cls):
	o: Dict[str, Any] = loads(dumps(TEST_DICT, encoder=encoder_cls), decoder=decoder_cls)
	assert o == loads(dumps(TEST_DICT, encoder=encoder_cls), decoder=decoder_cls)
Пример #12
0
def test_array_sep(encoder_cls):
	d = {'a': [1, 2, 3]}
	o: Dict[str, Any] = loads(dumps(d, encoder=encoder_cls))
	assert o == loads(dumps(o, encoder=encoder_cls))
Пример #13
0
    def test_dumps_encoder_none(self):

        with pytest.warns(DeprecationWarning, match=self.match):
            assert dom_toml.dumps(
                {"hello": "world"},
                encoder=None) == self.expected  # type: ignore[arg-type]