1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282
|
import toml
import copy
import pytest
import os
import sys
from decimal import Decimal
from toml.decoder import InlineTableDict
TEST_STR = """
[a]\r
b = 1\r
c = 2
"""
TEST_DICT = {"a": {"b": 1, "c": 2}}
def test_bug_148():
assert 'a = "\\u0064"\n' == toml.dumps({'a': '\\x64'})
assert 'a = "\\\\x64"\n' == toml.dumps({'a': '\\\\x64'})
assert 'a = "\\\\\\u0064"\n' == toml.dumps({'a': '\\\\\\x64'})
def test_bug_144():
if sys.version_info >= (3,):
return
bug_dict = {'username': '\xd7\xa9\xd7\x9c\xd7\x95\xd7\x9d'}
round_trip_bug_dict = toml.loads(toml.dumps(bug_dict))
unicoded_bug_dict = {'username': bug_dict['username'].decode('utf-8')}
assert round_trip_bug_dict == unicoded_bug_dict
assert bug_dict['username'] == (round_trip_bug_dict['username']
.encode('utf-8'))
def test_bug_196():
import datetime
d = datetime.datetime.now()
bug_dict = {'x': d}
round_trip_bug_dict = toml.loads(toml.dumps(bug_dict))
assert round_trip_bug_dict == bug_dict
assert round_trip_bug_dict['x'] == bug_dict['x']
def test_valid_tests():
valid_dir = "toml-test/tests/valid/"
for f in os.listdir(valid_dir):
if not f.endswith("toml"):
continue
with open(os.path.join(valid_dir, f)) as fh:
toml.dumps(toml.load(fh))
def test_circular_ref():
a = {}
b = {}
b['c'] = 4
b['self'] = b
a['b'] = b
with pytest.raises(ValueError):
toml.dumps(a)
with pytest.raises(ValueError):
toml.dumps(b)
def test__dict():
class TestDict(dict):
pass
assert isinstance(toml.loads(
TEST_STR, _dict=TestDict), TestDict)
def test_dict_decoder():
class TestDict(dict):
pass
test_dict_decoder = toml.TomlDecoder(TestDict)
assert isinstance(toml.loads(
TEST_STR, decoder=test_dict_decoder), TestDict)
def test_inline_dict():
class TestDict(dict, InlineTableDict):
pass
encoder = toml.TomlPreserveInlineDictEncoder()
t = copy.deepcopy(TEST_DICT)
t['d'] = TestDict()
t['d']['x'] = "abc"
o = toml.loads(toml.dumps(t, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
def test_array_sep():
encoder = toml.TomlArraySeparatorEncoder(separator=",\t")
d = {"a": [1, 2, 3]}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
def test_numpy_floats():
np = pytest.importorskip('numpy')
encoder = toml.TomlNumpyEncoder()
d = {'a': np.array([1, .3], dtype=np.float64)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
d = {'a': np.array([1, .3], dtype=np.float32)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
d = {'a': np.array([1, .3], dtype=np.float16)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
def test_numpy_ints():
np = pytest.importorskip('numpy')
encoder = toml.TomlNumpyEncoder()
d = {'a': np.array([1, 3], dtype=np.int64)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
d = {'a': np.array([1, 3], dtype=np.int32)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
d = {'a': np.array([1, 3], dtype=np.int16)}
o = toml.loads(toml.dumps(d, encoder=encoder))
assert o == toml.loads(toml.dumps(o, encoder=encoder))
def test_ordered():
from toml import ordered as toml_ordered
encoder = toml_ordered.TomlOrderedEncoder()
decoder = toml_ordered.TomlOrderedDecoder()
o = toml.loads(toml.dumps(TEST_DICT, encoder=encoder), decoder=decoder)
assert o == toml.loads(toml.dumps(TEST_DICT, encoder=encoder),
decoder=decoder)
def test_tuple():
d = {"a": (3, 4)}
o = toml.loads(toml.dumps(d))
assert o == toml.loads(toml.dumps(o))
def test_decimal():
PLACES = Decimal(10) ** -4
d = {"a": Decimal("0.1")}
o = toml.loads(toml.dumps(d))
assert o == toml.loads(toml.dumps(o))
assert Decimal(o["a"]).quantize(PLACES) == d["a"].quantize(PLACES)
def test_invalid_tests():
invalid_dir = "toml-test/tests/invalid/"
for f in os.listdir(invalid_dir):
if not f.endswith("toml"):
continue
with pytest.raises(toml.TomlDecodeError):
with open(os.path.join(invalid_dir, f)) as fh:
toml.load(fh)
def test_exceptions():
with pytest.raises(TypeError):
toml.loads(2)
with pytest.raises(TypeError):
toml.load(2)
try:
FNFError = FileNotFoundError
except NameError:
# py2
FNFError = IOError
with pytest.raises(FNFError):
toml.load([])
class FakeFile(object):
def __init__(self):
self.written = ""
def write(self, s):
self.written += s
return None
def read(self):
return self.written
def test_dump():
from collections import OrderedDict
f = FakeFile()
g = FakeFile()
h = FakeFile()
toml.dump(TEST_DICT, f)
toml.dump(toml.load(f, _dict=OrderedDict), g)
toml.dump(toml.load(g, _dict=OrderedDict), h)
assert g.written == h.written
def test_paths():
toml.load("test.toml")
toml.load(b"test.toml")
import sys
if (3, 4) <= sys.version_info:
import pathlib
p = pathlib.Path("test.toml")
toml.load(p)
def test_warnings():
# Expect 1 warning for the non existent toml file
with pytest.warns(UserWarning):
toml.load(["test.toml", "nonexist.toml"])
def test_commutativity():
o = toml.loads(toml.dumps(TEST_DICT))
assert o == toml.loads(toml.dumps(o))
def test_pathlib():
if (3, 4) <= sys.version_info:
import pathlib
o = {"root": {"path": pathlib.Path("/home/edgy")}}
test_str = """[root]
path = "/home/edgy"
"""
assert test_str == toml.dumps(o, encoder=toml.TomlPathlibEncoder())
def test_comment_preserve_decoder_encoder():
test_str = """[[products]]
name = "Nail"
sku = 284758393
# This is a comment
color = "gray" # Hello World
# name = { first = 'Tom', last = 'Preston-Werner' }
# arr7 = [
# 1, 2, 3
# ]
# lines = '''
# The first newline is
# trimmed in raw strings.
# All other whitespace
# is preserved.
# '''
[animals]
color = "gray" # col
fruits = "apple" # a = [1,2,3]
a = 3
b-comment = "a is 3"
"""
s = toml.dumps(toml.loads(test_str,
decoder=toml.TomlPreserveCommentDecoder()),
encoder=toml.TomlPreserveCommentEncoder())
assert len(s) == len(test_str) and sorted(test_str) == sorted(s)
def test_deepcopy_timezone():
import copy
o = toml.loads("dob = 1979-05-24T07:32:00-08:00")
o2 = copy.deepcopy(o)
assert o2["dob"] == o["dob"]
assert o2["dob"] is not o["dob"]
|