| 1 |
# Copyright (c) 2010-2024 Benjamin Peterson |
| 2 |
# |
| 3 |
# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 |
# of this software and associated documentation files (the "Software"), to deal |
| 5 |
# in the Software without restriction, including without limitation the rights |
| 6 |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 |
# copies of the Software, and to permit persons to whom the Software is |
| 8 |
# furnished to do so, subject to the following conditions: |
| 9 |
# |
| 10 |
# The above copyright notice and this permission notice shall be included in all |
| 11 |
# copies or substantial portions of the Software. |
| 12 |
# |
| 13 |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 18 |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 19 |
# SOFTWARE. |
| 20 |
|
| 21 |
import operator |
| 22 |
import sys |
| 23 |
import types |
| 24 |
import unittest |
| 25 |
import abc |
| 26 |
|
| 27 |
import pytest |
| 28 |
|
| 29 |
import six |
| 30 |
|
| 31 |
|
| 32 |
def test_add_doc(): |
| 33 |
def f(): |
| 34 |
"""Icky doc""" |
| 35 |
pass |
| 36 |
six._add_doc(f, """New doc""") |
| 37 |
assert f.__doc__ == "New doc" |
| 38 |
|
| 39 |
|
| 40 |
def test_import_module(): |
| 41 |
from logging import handlers |
| 42 |
m = six._import_module("logging.handlers") |
| 43 |
assert m is handlers |
| 44 |
|
| 45 |
|
| 46 |
def test_integer_types(): |
| 47 |
assert isinstance(1, six.integer_types) |
| 48 |
assert isinstance(-1, six.integer_types) |
| 49 |
assert isinstance(six.MAXSIZE + 23, six.integer_types) |
| 50 |
assert not isinstance(.1, six.integer_types) |
| 51 |
|
| 52 |
|
| 53 |
def test_string_types(): |
| 54 |
assert isinstance("hi", six.string_types) |
| 55 |
assert isinstance(six.u("hi"), six.string_types) |
| 56 |
assert issubclass(six.text_type, six.string_types) |
| 57 |
|
| 58 |
|
| 59 |
def test_class_types(): |
| 60 |
class X: |
| 61 |
pass |
| 62 |
class Y(object): |
| 63 |
pass |
| 64 |
assert isinstance(X, six.class_types) |
| 65 |
assert isinstance(Y, six.class_types) |
| 66 |
assert not isinstance(X(), six.class_types) |
| 67 |
|
| 68 |
|
| 69 |
def test_text_type(): |
| 70 |
assert type(six.u("hi")) is six.text_type |
| 71 |
|
| 72 |
|
| 73 |
def test_binary_type(): |
| 74 |
assert type(six.b("hi")) is six.binary_type |
| 75 |
|
| 76 |
|
| 77 |
def test_MAXSIZE(): |
| 78 |
try: |
| 79 |
# This shouldn't raise an overflow error. |
| 80 |
six.MAXSIZE.__index__() |
| 81 |
except AttributeError: |
| 82 |
# Before Python 2.6. |
| 83 |
pass |
| 84 |
pytest.raises( |
| 85 |
(ValueError, OverflowError), |
| 86 |
operator.mul, [None], six.MAXSIZE + 1) |
| 87 |
|
| 88 |
|
| 89 |
def test_lazy(): |
| 90 |
if six.PY3: |
| 91 |
html_name = "html.parser" |
| 92 |
else: |
| 93 |
html_name = "HTMLParser" |
| 94 |
assert html_name not in sys.modules |
| 95 |
mod = six.moves.html_parser |
| 96 |
assert sys.modules[html_name] is mod |
| 97 |
assert "htmlparser" not in six._MovedItems.__dict__ |
| 98 |
|
| 99 |
|
| 100 |
try: |
| 101 |
import _tkinter |
| 102 |
except ImportError: |
| 103 |
have_tkinter = False |
| 104 |
else: |
| 105 |
have_tkinter = True |
| 106 |
|
| 107 |
have_gdbm = True |
| 108 |
try: |
| 109 |
import gdbm |
| 110 |
except ImportError: |
| 111 |
try: |
| 112 |
import dbm.gnu |
| 113 |
except ImportError: |
| 114 |
have_gdbm = False |
| 115 |
|
| 116 |
have_ndbm = True |
| 117 |
try: |
| 118 |
import dbm |
| 119 |
except ImportError: |
| 120 |
try: |
| 121 |
import dbm.ndbm |
| 122 |
except ImportError: |
| 123 |
have_ndbm = False |
| 124 |
|
| 125 |
@pytest.mark.parametrize("item_name", |
| 126 |
[item.name for item in six._moved_attributes]) |
| 127 |
def test_move_items(item_name): |
| 128 |
"""Ensure that everything loads correctly.""" |
| 129 |
try: |
| 130 |
item = getattr(six.moves, item_name) |
| 131 |
if isinstance(item, types.ModuleType): |
| 132 |
__import__("six.moves." + item_name) |
| 133 |
except ImportError: |
| 134 |
if item_name == "winreg" and not sys.platform.startswith("win"): |
| 135 |
pytest.skip("Windows only module") |
| 136 |
if item_name.startswith("tkinter"): |
| 137 |
if not have_tkinter: |
| 138 |
pytest.skip("requires tkinter") |
| 139 |
if item_name == "tkinter_tix" and sys.version_info >= (3, 13): |
| 140 |
pytest.skip("tkinter.tix removed from Python 3.13") |
| 141 |
if item_name == "dbm_gnu" and not have_gdbm: |
| 142 |
pytest.skip("requires gdbm") |
| 143 |
if item_name == "dbm_ndbm": |
| 144 |
pytest.skip("requires ndbm") |
| 145 |
raise |
| 146 |
assert item_name in dir(six.moves) |
| 147 |
|
| 148 |
|
| 149 |
@pytest.mark.parametrize("item_name", |
| 150 |
[item.name for item in six._urllib_parse_moved_attributes]) |
| 151 |
def test_move_items_urllib_parse(item_name): |
| 152 |
"""Ensure that everything loads correctly.""" |
| 153 |
assert item_name in dir(six.moves.urllib.parse) |
| 154 |
getattr(six.moves.urllib.parse, item_name) |
| 155 |
|
| 156 |
|
| 157 |
@pytest.mark.parametrize("item_name", |
| 158 |
[item.name for item in six._urllib_error_moved_attributes]) |
| 159 |
def test_move_items_urllib_error(item_name): |
| 160 |
"""Ensure that everything loads correctly.""" |
| 161 |
assert item_name in dir(six.moves.urllib.error) |
| 162 |
getattr(six.moves.urllib.error, item_name) |
| 163 |
|
| 164 |
|
| 165 |
@pytest.mark.parametrize("item_name", |
| 166 |
[item.name for item in six._urllib_request_moved_attributes]) |
| 167 |
def test_move_items_urllib_request(item_name): |
| 168 |
"""Ensure that everything loads correctly.""" |
| 169 |
assert item_name in dir(six.moves.urllib.request) |
| 170 |
getattr(six.moves.urllib.request, item_name) |
| 171 |
|
| 172 |
|
| 173 |
@pytest.mark.parametrize("item_name", |
| 174 |
[item.name for item in six._urllib_response_moved_attributes]) |
| 175 |
def test_move_items_urllib_response(item_name): |
| 176 |
"""Ensure that everything loads correctly.""" |
| 177 |
assert item_name in dir(six.moves.urllib.response) |
| 178 |
getattr(six.moves.urllib.response, item_name) |
| 179 |
|
| 180 |
|
| 181 |
@pytest.mark.parametrize("item_name", |
| 182 |
[item.name for item in six._urllib_robotparser_moved_attributes]) |
| 183 |
def test_move_items_urllib_robotparser(item_name): |
| 184 |
"""Ensure that everything loads correctly.""" |
| 185 |
assert item_name in dir(six.moves.urllib.robotparser) |
| 186 |
getattr(six.moves.urllib.robotparser, item_name) |
| 187 |
|
| 188 |
|
| 189 |
def test_import_moves_error_1(): |
| 190 |
from six.moves.urllib.parse import urljoin |
| 191 |
from six import moves |
| 192 |
# In 1.4.1: AttributeError: 'Module_six_moves_urllib_parse' object has no attribute 'urljoin' |
| 193 |
assert moves.urllib.parse.urljoin |
| 194 |
|
| 195 |
|
| 196 |
def test_import_moves_error_2(): |
| 197 |
from six import moves |
| 198 |
assert moves.urllib.parse.urljoin |
| 199 |
# In 1.4.1: ImportError: cannot import name urljoin |
| 200 |
from six.moves.urllib.parse import urljoin |
| 201 |
|
| 202 |
|
| 203 |
def test_import_moves_error_3(): |
| 204 |
from six.moves.urllib.parse import urljoin |
| 205 |
# In 1.4.1: ImportError: cannot import name urljoin |
| 206 |
from six.moves.urllib_parse import urljoin |
| 207 |
|
| 208 |
|
| 209 |
def test_from_imports(): |
| 210 |
from six.moves.queue import Queue |
| 211 |
assert isinstance(Queue, six.class_types) |
| 212 |
from six.moves.configparser import ConfigParser |
| 213 |
assert isinstance(ConfigParser, six.class_types) |
| 214 |
|
| 215 |
|
| 216 |
def test_filter(): |
| 217 |
from six.moves import filter |
| 218 |
f = filter(lambda x: x % 2, range(10)) |
| 219 |
assert six.advance_iterator(f) == 1 |
| 220 |
|
| 221 |
|
| 222 |
def test_filter_false(): |
| 223 |
from six.moves import filterfalse |
| 224 |
f = filterfalse(lambda x: x % 3, range(10)) |
| 225 |
assert six.advance_iterator(f) == 0 |
| 226 |
assert six.advance_iterator(f) == 3 |
| 227 |
assert six.advance_iterator(f) == 6 |
| 228 |
|
| 229 |
def test_map(): |
| 230 |
from six.moves import map |
| 231 |
assert six.advance_iterator(map(lambda x: x + 1, range(2))) == 1 |
| 232 |
|
| 233 |
|
| 234 |
def test_getoutput(): |
| 235 |
from six.moves import getoutput |
| 236 |
output = getoutput('dir' if sys.platform.startswith('win') else 'echo foo') |
| 237 |
assert output != '' |
| 238 |
|
| 239 |
|
| 240 |
def test_zip(): |
| 241 |
from six.moves import zip |
| 242 |
assert six.advance_iterator(zip(range(2), range(2))) == (0, 0) |
| 243 |
|
| 244 |
|
| 245 |
def test_zip_longest(): |
| 246 |
from six.moves import zip_longest |
| 247 |
it = zip_longest(range(2), range(1)) |
| 248 |
|
| 249 |
assert six.advance_iterator(it) == (0, 0) |
| 250 |
assert six.advance_iterator(it) == (1, None) |
| 251 |
|
| 252 |
|
| 253 |
class TestCustomizedMoves: |
| 254 |
|
| 255 |
def teardown_method(self, meth): |
| 256 |
try: |
| 257 |
del six._MovedItems.spam |
| 258 |
except AttributeError: |
| 259 |
pass |
| 260 |
try: |
| 261 |
del six.moves.__dict__["spam"] |
| 262 |
except KeyError: |
| 263 |
pass |
| 264 |
|
| 265 |
|
| 266 |
def test_moved_attribute(self): |
| 267 |
attr = six.MovedAttribute("spam", "foo", "bar") |
| 268 |
if six.PY3: |
| 269 |
assert attr.mod == "bar" |
| 270 |
else: |
| 271 |
assert attr.mod == "foo" |
| 272 |
assert attr.attr == "spam" |
| 273 |
attr = six.MovedAttribute("spam", "foo", "bar", "lemma") |
| 274 |
assert attr.attr == "lemma" |
| 275 |
attr = six.MovedAttribute("spam", "foo", "bar", "lemma", "theorm") |
| 276 |
if six.PY3: |
| 277 |
assert attr.attr == "theorm" |
| 278 |
else: |
| 279 |
assert attr.attr == "lemma" |
| 280 |
|
| 281 |
|
| 282 |
def test_moved_module(self): |
| 283 |
attr = six.MovedModule("spam", "foo") |
| 284 |
if six.PY3: |
| 285 |
assert attr.mod == "spam" |
| 286 |
else: |
| 287 |
assert attr.mod == "foo" |
| 288 |
attr = six.MovedModule("spam", "foo", "bar") |
| 289 |
if six.PY3: |
| 290 |
assert attr.mod == "bar" |
| 291 |
else: |
| 292 |
assert attr.mod == "foo" |
| 293 |
|
| 294 |
|
| 295 |
def test_custom_move_module(self): |
| 296 |
attr = six.MovedModule("spam", "six", "six") |
| 297 |
six.add_move(attr) |
| 298 |
six.remove_move("spam") |
| 299 |
assert not hasattr(six.moves, "spam") |
| 300 |
attr = six.MovedModule("spam", "six", "six") |
| 301 |
six.add_move(attr) |
| 302 |
from six.moves import spam |
| 303 |
assert spam is six |
| 304 |
six.remove_move("spam") |
| 305 |
assert not hasattr(six.moves, "spam") |
| 306 |
|
| 307 |
|
| 308 |
def test_custom_move_attribute(self): |
| 309 |
attr = six.MovedAttribute("spam", "six", "six", "u", "u") |
| 310 |
six.add_move(attr) |
| 311 |
six.remove_move("spam") |
| 312 |
assert not hasattr(six.moves, "spam") |
| 313 |
attr = six.MovedAttribute("spam", "six", "six", "u", "u") |
| 314 |
six.add_move(attr) |
| 315 |
from six.moves import spam |
| 316 |
assert spam is six.u |
| 317 |
six.remove_move("spam") |
| 318 |
assert not hasattr(six.moves, "spam") |
| 319 |
|
| 320 |
|
| 321 |
def test_empty_remove(self): |
| 322 |
pytest.raises(AttributeError, six.remove_move, "eggs") |
| 323 |
|
| 324 |
|
| 325 |
def test_get_unbound_function(): |
| 326 |
class X(object): |
| 327 |
def m(self): |
| 328 |
pass |
| 329 |
assert six.get_unbound_function(X.m) is X.__dict__["m"] |
| 330 |
|
| 331 |
|
| 332 |
def test_get_method_self(): |
| 333 |
class X(object): |
| 334 |
def m(self): |
| 335 |
pass |
| 336 |
x = X() |
| 337 |
assert six.get_method_self(x.m) is x |
| 338 |
pytest.raises(AttributeError, six.get_method_self, 42) |
| 339 |
|
| 340 |
|
| 341 |
def test_get_method_function(): |
| 342 |
class X(object): |
| 343 |
def m(self): |
| 344 |
pass |
| 345 |
x = X() |
| 346 |
assert six.get_method_function(x.m) is X.__dict__["m"] |
| 347 |
pytest.raises(AttributeError, six.get_method_function, hasattr) |
| 348 |
|
| 349 |
|
| 350 |
def test_get_function_closure(): |
| 351 |
def f(): |
| 352 |
x = 42 |
| 353 |
def g(): |
| 354 |
return x |
| 355 |
return g |
| 356 |
cell = six.get_function_closure(f())[0] |
| 357 |
assert type(cell).__name__ == "cell" |
| 358 |
|
| 359 |
|
| 360 |
def test_get_function_code(): |
| 361 |
def f(): |
| 362 |
pass |
| 363 |
assert isinstance(six.get_function_code(f), types.CodeType) |
| 364 |
if not hasattr(sys, "pypy_version_info"): |
| 365 |
pytest.raises(AttributeError, six.get_function_code, hasattr) |
| 366 |
|
| 367 |
|
| 368 |
def test_get_function_defaults(): |
| 369 |
def f(x, y=3, b=4): |
| 370 |
pass |
| 371 |
assert six.get_function_defaults(f) == (3, 4) |
| 372 |
|
| 373 |
|
| 374 |
def test_get_function_globals(): |
| 375 |
def f(): |
| 376 |
pass |
| 377 |
assert six.get_function_globals(f) is globals() |
| 378 |
|
| 379 |
|
| 380 |
def test_dictionary_iterators(monkeypatch): |
| 381 |
def stock_method_name(iterwhat): |
| 382 |
"""Given a method suffix like "lists" or "values", return the name |
| 383 |
of the dict method that delivers those on the version of Python |
| 384 |
we're running in.""" |
| 385 |
if six.PY3: |
| 386 |
return iterwhat |
| 387 |
return 'iter' + iterwhat |
| 388 |
|
| 389 |
class MyDict(dict): |
| 390 |
if not six.PY3: |
| 391 |
def lists(self, **kw): |
| 392 |
return [1, 2, 3] |
| 393 |
def iterlists(self, **kw): |
| 394 |
return iter([1, 2, 3]) |
| 395 |
f = MyDict.iterlists |
| 396 |
del MyDict.iterlists |
| 397 |
setattr(MyDict, stock_method_name('lists'), f) |
| 398 |
|
| 399 |
d = MyDict(zip(range(10), reversed(range(10)))) |
| 400 |
for name in "keys", "values", "items", "lists": |
| 401 |
meth = getattr(six, "iter" + name) |
| 402 |
it = meth(d) |
| 403 |
assert not isinstance(it, list) |
| 404 |
assert list(it) == list(getattr(d, name)()) |
| 405 |
pytest.raises(StopIteration, six.advance_iterator, it) |
| 406 |
record = [] |
| 407 |
def with_kw(*args, **kw): |
| 408 |
record.append(kw["kw"]) |
| 409 |
return old(*args) |
| 410 |
old = getattr(MyDict, stock_method_name(name)) |
| 411 |
monkeypatch.setattr(MyDict, stock_method_name(name), with_kw) |
| 412 |
meth(d, kw=42) |
| 413 |
assert record == [42] |
| 414 |
monkeypatch.undo() |
| 415 |
|
| 416 |
|
| 417 |
def test_dictionary_views(): |
| 418 |
d = dict(zip(range(10), (range(11, 20)))) |
| 419 |
for name in "keys", "values", "items": |
| 420 |
meth = getattr(six, "view" + name) |
| 421 |
view = meth(d) |
| 422 |
assert set(view) == set(getattr(d, name)()) |
| 423 |
|
| 424 |
|
| 425 |
def test_advance_iterator(): |
| 426 |
assert six.next is six.advance_iterator |
| 427 |
l = [1, 2] |
| 428 |
it = iter(l) |
| 429 |
assert six.next(it) == 1 |
| 430 |
assert six.next(it) == 2 |
| 431 |
pytest.raises(StopIteration, six.next, it) |
| 432 |
pytest.raises(StopIteration, six.next, it) |
| 433 |
|
| 434 |
|
| 435 |
def test_iterator(): |
| 436 |
class myiter(six.Iterator): |
| 437 |
def __next__(self): |
| 438 |
return 13 |
| 439 |
assert six.advance_iterator(myiter()) == 13 |
| 440 |
class myitersub(myiter): |
| 441 |
def __next__(self): |
| 442 |
return 14 |
| 443 |
assert six.advance_iterator(myitersub()) == 14 |
| 444 |
|
| 445 |
|
| 446 |
def test_callable(): |
| 447 |
class X: |
| 448 |
def __call__(self): |
| 449 |
pass |
| 450 |
def method(self): |
| 451 |
pass |
| 452 |
assert six.callable(X) |
| 453 |
assert six.callable(X()) |
| 454 |
assert six.callable(test_callable) |
| 455 |
assert six.callable(hasattr) |
| 456 |
assert six.callable(X.method) |
| 457 |
assert six.callable(X().method) |
| 458 |
assert not six.callable(4) |
| 459 |
assert not six.callable("string") |
| 460 |
|
| 461 |
|
| 462 |
def test_create_bound_method(): |
| 463 |
class X(object): |
| 464 |
pass |
| 465 |
def f(self): |
| 466 |
return self |
| 467 |
x = X() |
| 468 |
b = six.create_bound_method(f, x) |
| 469 |
assert isinstance(b, types.MethodType) |
| 470 |
assert b() is x |
| 471 |
|
| 472 |
|
| 473 |
def test_create_unbound_method(): |
| 474 |
class X(object): |
| 475 |
pass |
| 476 |
|
| 477 |
def f(self): |
| 478 |
return self |
| 479 |
u = six.create_unbound_method(f, X) |
| 480 |
pytest.raises(TypeError, u) |
| 481 |
if six.PY2: |
| 482 |
assert isinstance(u, types.MethodType) |
| 483 |
x = X() |
| 484 |
assert f(x) is x |
| 485 |
|
| 486 |
|
| 487 |
if six.PY3: |
| 488 |
|
| 489 |
def test_b(): |
| 490 |
data = six.b("\xff") |
| 491 |
assert isinstance(data, bytes) |
| 492 |
assert len(data) == 1 |
| 493 |
assert data == bytes([255]) |
| 494 |
|
| 495 |
|
| 496 |
def test_u(): |
| 497 |
s = six.u("hi \u0439 \U00000439 \\ \\\\ \n") |
| 498 |
assert isinstance(s, str) |
| 499 |
assert s == "hi \u0439 \U00000439 \\ \\\\ \n" |
| 500 |
|
| 501 |
else: |
| 502 |
|
| 503 |
def test_b(): |
| 504 |
data = six.b("\xff") |
| 505 |
assert isinstance(data, str) |
| 506 |
assert len(data) == 1 |
| 507 |
assert data == "\xff" |
| 508 |
|
| 509 |
|
| 510 |
def test_u(): |
| 511 |
s = six.u("hi \u0439 \U00000439 \\ \\\\ \n") |
| 512 |
assert isinstance(s, unicode) |
| 513 |
assert s == "hi \xd0\xb9 \xd0\xb9 \\ \\\\ \n".decode("utf8") |
| 514 |
|
| 515 |
|
| 516 |
def test_u_escapes(): |
| 517 |
s = six.u("\u1234") |
| 518 |
assert len(s) == 1 |
| 519 |
|
| 520 |
|
| 521 |
def test_unichr(): |
| 522 |
assert six.u("\u1234") == six.unichr(0x1234) |
| 523 |
assert type(six.u("\u1234")) is type(six.unichr(0x1234)) |
| 524 |
|
| 525 |
|
| 526 |
def test_int2byte(): |
| 527 |
assert six.int2byte(3) == six.b("\x03") |
| 528 |
pytest.raises(Exception, six.int2byte, 256) |
| 529 |
|
| 530 |
|
| 531 |
def test_byte2int(): |
| 532 |
assert six.byte2int(six.b("\x03")) == 3 |
| 533 |
assert six.byte2int(six.b("\x03\x04")) == 3 |
| 534 |
pytest.raises(IndexError, six.byte2int, six.b("")) |
| 535 |
|
| 536 |
|
| 537 |
def test_bytesindex(): |
| 538 |
assert six.indexbytes(six.b("hello"), 3) == ord("l") |
| 539 |
|
| 540 |
|
| 541 |
def test_bytesiter(): |
| 542 |
it = six.iterbytes(six.b("hi")) |
| 543 |
assert six.next(it) == ord("h") |
| 544 |
assert six.next(it) == ord("i") |
| 545 |
pytest.raises(StopIteration, six.next, it) |
| 546 |
|
| 547 |
|
| 548 |
def test_StringIO(): |
| 549 |
fp = six.StringIO() |
| 550 |
fp.write(six.u("hello")) |
| 551 |
assert fp.getvalue() == six.u("hello") |
| 552 |
|
| 553 |
|
| 554 |
def test_BytesIO(): |
| 555 |
fp = six.BytesIO() |
| 556 |
fp.write(six.b("hello")) |
| 557 |
assert fp.getvalue() == six.b("hello") |
| 558 |
|
| 559 |
|
| 560 |
def test_exec_(): |
| 561 |
def f(): |
| 562 |
l = [] |
| 563 |
six.exec_("l.append(1)") |
| 564 |
assert l == [1] |
| 565 |
f() |
| 566 |
ns = {} |
| 567 |
six.exec_("x = 42", ns) |
| 568 |
assert ns["x"] == 42 |
| 569 |
glob = {} |
| 570 |
loc = {} |
| 571 |
six.exec_("global y; y = 42; x = 12", glob, loc) |
| 572 |
assert glob["y"] == 42 |
| 573 |
assert "x" not in glob |
| 574 |
assert loc["x"] == 12 |
| 575 |
assert "y" not in loc |
| 576 |
|
| 577 |
|
| 578 |
def test_reraise(): |
| 579 |
def get_next(tb): |
| 580 |
if six.PY3: |
| 581 |
return tb.tb_next.tb_next |
| 582 |
else: |
| 583 |
return tb.tb_next |
| 584 |
e = Exception("blah") |
| 585 |
try: |
| 586 |
raise e |
| 587 |
except Exception: |
| 588 |
tp, val, tb = sys.exc_info() |
| 589 |
try: |
| 590 |
six.reraise(tp, val, tb) |
| 591 |
except Exception: |
| 592 |
tp2, value2, tb2 = sys.exc_info() |
| 593 |
assert tp2 is Exception |
| 594 |
assert value2 is e |
| 595 |
assert tb is get_next(tb2) |
| 596 |
try: |
| 597 |
six.reraise(tp, val) |
| 598 |
except Exception: |
| 599 |
tp2, value2, tb2 = sys.exc_info() |
| 600 |
assert tp2 is Exception |
| 601 |
assert value2 is e |
| 602 |
assert tb2 is not tb |
| 603 |
try: |
| 604 |
six.reraise(tp, val, tb2) |
| 605 |
except Exception: |
| 606 |
tp2, value2, tb3 = sys.exc_info() |
| 607 |
assert tp2 is Exception |
| 608 |
assert value2 is e |
| 609 |
assert get_next(tb3) is tb2 |
| 610 |
try: |
| 611 |
six.reraise(tp, None, tb) |
| 612 |
except Exception: |
| 613 |
tp2, value2, tb2 = sys.exc_info() |
| 614 |
assert tp2 is Exception |
| 615 |
assert value2 is not val |
| 616 |
assert isinstance(value2, Exception) |
| 617 |
assert tb is get_next(tb2) |
| 618 |
|
| 619 |
|
| 620 |
def test_raise_from(): |
| 621 |
try: |
| 622 |
try: |
| 623 |
raise Exception("blah") |
| 624 |
except Exception: |
| 625 |
ctx = sys.exc_info()[1] |
| 626 |
f = Exception("foo") |
| 627 |
six.raise_from(f, None) |
| 628 |
except Exception: |
| 629 |
tp, val, tb = sys.exc_info() |
| 630 |
if sys.version_info[:2] > (3, 0): |
| 631 |
# We should have done a raise f from None equivalent. |
| 632 |
assert val.__cause__ is None |
| 633 |
assert val.__context__ is ctx |
| 634 |
# And that should suppress the context on the exception. |
| 635 |
assert val.__suppress_context__ |
| 636 |
# For all versions the outer exception should have raised successfully. |
| 637 |
assert str(val) == "foo" |
| 638 |
|
| 639 |
|
| 640 |
def test_print_(): |
| 641 |
save = sys.stdout |
| 642 |
out = sys.stdout = six.moves.StringIO() |
| 643 |
try: |
| 644 |
six.print_("Hello,", "person!") |
| 645 |
finally: |
| 646 |
sys.stdout = save |
| 647 |
assert out.getvalue() == "Hello, person!\n" |
| 648 |
out = six.StringIO() |
| 649 |
six.print_("Hello,", "person!", file=out) |
| 650 |
assert out.getvalue() == "Hello, person!\n" |
| 651 |
out = six.StringIO() |
| 652 |
six.print_("Hello,", "person!", file=out, end="") |
| 653 |
assert out.getvalue() == "Hello, person!" |
| 654 |
out = six.StringIO() |
| 655 |
six.print_("Hello,", "person!", file=out, sep="X") |
| 656 |
assert out.getvalue() == "Hello,Xperson!\n" |
| 657 |
out = six.StringIO() |
| 658 |
six.print_(six.u("Hello,"), six.u("person!"), file=out) |
| 659 |
result = out.getvalue() |
| 660 |
assert isinstance(result, six.text_type) |
| 661 |
assert result == six.u("Hello, person!\n") |
| 662 |
six.print_("Hello", file=None) # This works. |
| 663 |
out = six.StringIO() |
| 664 |
six.print_(None, file=out) |
| 665 |
assert out.getvalue() == "None\n" |
| 666 |
class FlushableStringIO(six.StringIO): |
| 667 |
def __init__(self): |
| 668 |
six.StringIO.__init__(self) |
| 669 |
self.flushed = False |
| 670 |
def flush(self): |
| 671 |
self.flushed = True |
| 672 |
out = FlushableStringIO() |
| 673 |
six.print_("Hello", file=out) |
| 674 |
assert not out.flushed |
| 675 |
six.print_("Hello", file=out, flush=True) |
| 676 |
assert out.flushed |
| 677 |
|
| 678 |
|
| 679 |
def test_print_exceptions(): |
| 680 |
pytest.raises(TypeError, six.print_, x=3) |
| 681 |
pytest.raises(TypeError, six.print_, end=3) |
| 682 |
pytest.raises(TypeError, six.print_, sep=42) |
| 683 |
|
| 684 |
|
| 685 |
def test_with_metaclass(): |
| 686 |
class Meta(type): |
| 687 |
pass |
| 688 |
class X(six.with_metaclass(Meta)): |
| 689 |
pass |
| 690 |
assert type(X) is Meta |
| 691 |
assert issubclass(X, object) |
| 692 |
class Base(object): |
| 693 |
pass |
| 694 |
class X(six.with_metaclass(Meta, Base)): |
| 695 |
pass |
| 696 |
assert type(X) is Meta |
| 697 |
assert issubclass(X, Base) |
| 698 |
class Base2(object): |
| 699 |
pass |
| 700 |
class X(six.with_metaclass(Meta, Base, Base2)): |
| 701 |
pass |
| 702 |
assert type(X) is Meta |
| 703 |
assert issubclass(X, Base) |
| 704 |
assert issubclass(X, Base2) |
| 705 |
assert X.__mro__ == (X, Base, Base2, object) |
| 706 |
class X(six.with_metaclass(Meta)): |
| 707 |
pass |
| 708 |
class MetaSub(Meta): |
| 709 |
pass |
| 710 |
class Y(six.with_metaclass(MetaSub, X)): |
| 711 |
pass |
| 712 |
assert type(Y) is MetaSub |
| 713 |
assert Y.__mro__ == (Y, X, object) |
| 714 |
|
| 715 |
|
| 716 |
def test_with_metaclass_typing(): |
| 717 |
try: |
| 718 |
import typing |
| 719 |
except ImportError: |
| 720 |
pytest.skip("typing module required") |
| 721 |
class Meta(type): |
| 722 |
pass |
| 723 |
if sys.version_info[:2] < (3, 7): |
| 724 |
# Generics with custom metaclasses were broken on older versions. |
| 725 |
class Meta(Meta, typing.GenericMeta): |
| 726 |
pass |
| 727 |
T = typing.TypeVar('T') |
| 728 |
class G(six.with_metaclass(Meta, typing.Generic[T])): |
| 729 |
pass |
| 730 |
class GA(six.with_metaclass(abc.ABCMeta, typing.Generic[T])): |
| 731 |
pass |
| 732 |
assert isinstance(G, Meta) |
| 733 |
assert isinstance(GA, abc.ABCMeta) |
| 734 |
assert G[int] is not G[G[int]] |
| 735 |
assert GA[int] is not GA[GA[int]] |
| 736 |
assert G.__bases__ == (typing.Generic,) |
| 737 |
assert G.__orig_bases__ == (typing.Generic[T],) |
| 738 |
|
| 739 |
|
| 740 |
@pytest.mark.skipif("sys.version_info[:2] < (3, 7)") |
| 741 |
def test_with_metaclass_pep_560(): |
| 742 |
class Meta(type): |
| 743 |
pass |
| 744 |
class A: |
| 745 |
pass |
| 746 |
class B: |
| 747 |
pass |
| 748 |
class Fake: |
| 749 |
def __mro_entries__(self, bases): |
| 750 |
return (A, B) |
| 751 |
fake = Fake() |
| 752 |
class G(six.with_metaclass(Meta, fake)): |
| 753 |
pass |
| 754 |
class GA(six.with_metaclass(abc.ABCMeta, fake)): |
| 755 |
pass |
| 756 |
assert isinstance(G, Meta) |
| 757 |
assert isinstance(GA, abc.ABCMeta) |
| 758 |
assert G.__bases__ == (A, B) |
| 759 |
assert G.__orig_bases__ == (fake,) |
| 760 |
|
| 761 |
|
| 762 |
@pytest.mark.skipif("sys.version_info[:2] < (3, 0)") |
| 763 |
def test_with_metaclass_prepare(): |
| 764 |
"""Test that with_metaclass causes Meta.__prepare__ to be called with the correct arguments.""" |
| 765 |
|
| 766 |
class MyDict(dict): |
| 767 |
pass |
| 768 |
|
| 769 |
class Meta(type): |
| 770 |
|
| 771 |
@classmethod |
| 772 |
def __prepare__(cls, name, bases): |
| 773 |
namespace = MyDict(super().__prepare__(name, bases), cls=cls, bases=bases) |
| 774 |
namespace['namespace'] = namespace |
| 775 |
return namespace |
| 776 |
|
| 777 |
class Base(object): |
| 778 |
pass |
| 779 |
|
| 780 |
bases = (Base,) |
| 781 |
|
| 782 |
class X(six.with_metaclass(Meta, *bases)): |
| 783 |
pass |
| 784 |
|
| 785 |
assert getattr(X, 'cls', type) is Meta |
| 786 |
assert getattr(X, 'bases', ()) == bases |
| 787 |
assert isinstance(getattr(X, 'namespace', {}), MyDict) |
| 788 |
|
| 789 |
|
| 790 |
def test_wraps(): |
| 791 |
def f(g): |
| 792 |
@six.wraps(g) |
| 793 |
def w(): |
| 794 |
return 42 |
| 795 |
return w |
| 796 |
def k(): |
| 797 |
pass |
| 798 |
original_k = k |
| 799 |
k = f(f(k)) |
| 800 |
assert hasattr(k, '__wrapped__') |
| 801 |
k = k.__wrapped__ |
| 802 |
assert hasattr(k, '__wrapped__') |
| 803 |
k = k.__wrapped__ |
| 804 |
assert k is original_k |
| 805 |
assert not hasattr(k, '__wrapped__') |
| 806 |
|
| 807 |
def f(g, assign, update): |
| 808 |
def w(): |
| 809 |
return 42 |
| 810 |
w.glue = {"foo": "bar"} |
| 811 |
w.xyzzy = {"qux": "quux"} |
| 812 |
return six.wraps(g, assign, update)(w) |
| 813 |
k.glue = {"melon": "egg"} |
| 814 |
k.turnip = 43 |
| 815 |
k = f(k, ["turnip", "baz"], ["glue", "xyzzy"]) |
| 816 |
assert k.__name__ == "w" |
| 817 |
assert k.turnip == 43 |
| 818 |
assert not hasattr(k, "baz") |
| 819 |
assert k.glue == {"melon": "egg", "foo": "bar"} |
| 820 |
assert k.xyzzy == {"qux": "quux"} |
| 821 |
|
| 822 |
|
| 823 |
def test_wraps_raises_on_missing_updated_field_on_wrapper(): |
| 824 |
"""Ensure six.wraps doesn't ignore missing attrs wrapper. |
| 825 |
|
| 826 |
Because that's what happens in Py3's functools.update_wrapper. |
| 827 |
""" |
| 828 |
def wrapped(): |
| 829 |
pass |
| 830 |
|
| 831 |
def wrapper(): |
| 832 |
pass |
| 833 |
|
| 834 |
with pytest.raises(AttributeError, match='has no attribute.*xyzzy'): |
| 835 |
six.wraps(wrapped, [], ['xyzzy'])(wrapper) |
| 836 |
|
| 837 |
|
| 838 |
|
| 839 |
def test_add_metaclass(): |
| 840 |
class Meta(type): |
| 841 |
pass |
| 842 |
class X: |
| 843 |
"success" |
| 844 |
X = six.add_metaclass(Meta)(X) |
| 845 |
assert type(X) is Meta |
| 846 |
assert issubclass(X, object) |
| 847 |
assert X.__module__ == __name__ |
| 848 |
assert X.__doc__ == "success" |
| 849 |
class Base(object): |
| 850 |
pass |
| 851 |
class X(Base): |
| 852 |
pass |
| 853 |
X = six.add_metaclass(Meta)(X) |
| 854 |
assert type(X) is Meta |
| 855 |
assert issubclass(X, Base) |
| 856 |
class Base2(object): |
| 857 |
pass |
| 858 |
class X(Base, Base2): |
| 859 |
pass |
| 860 |
X = six.add_metaclass(Meta)(X) |
| 861 |
assert type(X) is Meta |
| 862 |
assert issubclass(X, Base) |
| 863 |
assert issubclass(X, Base2) |
| 864 |
|
| 865 |
# Test a second-generation subclass of a type. |
| 866 |
class Meta1(type): |
| 867 |
m1 = "m1" |
| 868 |
class Meta2(Meta1): |
| 869 |
m2 = "m2" |
| 870 |
class Base: |
| 871 |
b = "b" |
| 872 |
Base = six.add_metaclass(Meta1)(Base) |
| 873 |
class X(Base): |
| 874 |
x = "x" |
| 875 |
X = six.add_metaclass(Meta2)(X) |
| 876 |
assert type(X) is Meta2 |
| 877 |
assert issubclass(X, Base) |
| 878 |
assert type(Base) is Meta1 |
| 879 |
assert "__dict__" not in vars(X) |
| 880 |
instance = X() |
| 881 |
instance.attr = "test" |
| 882 |
assert vars(instance) == {"attr": "test"} |
| 883 |
assert instance.b == Base.b |
| 884 |
assert instance.x == X.x |
| 885 |
|
| 886 |
# Test a class with slots. |
| 887 |
class MySlots(object): |
| 888 |
__slots__ = ["a", "b"] |
| 889 |
MySlots = six.add_metaclass(Meta1)(MySlots) |
| 890 |
|
| 891 |
assert MySlots.__slots__ == ["a", "b"] |
| 892 |
instance = MySlots() |
| 893 |
instance.a = "foo" |
| 894 |
pytest.raises(AttributeError, setattr, instance, "c", "baz") |
| 895 |
|
| 896 |
# Test a class with string for slots. |
| 897 |
class MyStringSlots(object): |
| 898 |
__slots__ = "ab" |
| 899 |
MyStringSlots = six.add_metaclass(Meta1)(MyStringSlots) |
| 900 |
assert MyStringSlots.__slots__ == "ab" |
| 901 |
instance = MyStringSlots() |
| 902 |
instance.ab = "foo" |
| 903 |
pytest.raises(AttributeError, setattr, instance, "a", "baz") |
| 904 |
pytest.raises(AttributeError, setattr, instance, "b", "baz") |
| 905 |
|
| 906 |
class MySlotsWeakref(object): |
| 907 |
__slots__ = "__weakref__", |
| 908 |
MySlotsWeakref = six.add_metaclass(Meta)(MySlotsWeakref) |
| 909 |
assert type(MySlotsWeakref) is Meta |
| 910 |
|
| 911 |
|
| 912 |
@pytest.mark.skipif("sys.version_info[:2] < (3, 3)") |
| 913 |
def test_add_metaclass_nested(): |
| 914 |
# Regression test for https://github.com/benjaminp/six/issues/259 |
| 915 |
class Meta(type): |
| 916 |
pass |
| 917 |
|
| 918 |
class A: |
| 919 |
class B: pass |
| 920 |
|
| 921 |
expected = 'test_add_metaclass_nested.<locals>.A.B' |
| 922 |
|
| 923 |
assert A.B.__qualname__ == expected |
| 924 |
|
| 925 |
class A: |
| 926 |
@six.add_metaclass(Meta) |
| 927 |
class B: pass |
| 928 |
|
| 929 |
assert A.B.__qualname__ == expected |
| 930 |
|
| 931 |
|
| 932 |
def test_assertCountEqual(): |
| 933 |
class TestAssertCountEqual(unittest.TestCase): |
| 934 |
def test(self): |
| 935 |
with self.assertRaises(AssertionError): |
| 936 |
six.assertCountEqual(self, (1, 2), [3, 4, 5]) |
| 937 |
|
| 938 |
six.assertCountEqual(self, (1, 2), [2, 1]) |
| 939 |
|
| 940 |
TestAssertCountEqual('test').test() |
| 941 |
|
| 942 |
|
| 943 |
def test_assertRegex(): |
| 944 |
class TestAssertRegex(unittest.TestCase): |
| 945 |
def test(self): |
| 946 |
with self.assertRaises(AssertionError): |
| 947 |
six.assertRegex(self, 'test', r'^a') |
| 948 |
|
| 949 |
six.assertRegex(self, 'test', r'^t') |
| 950 |
|
| 951 |
TestAssertRegex('test').test() |
| 952 |
|
| 953 |
|
| 954 |
def test_assertNotRegex(): |
| 955 |
class TestAssertNotRegex(unittest.TestCase): |
| 956 |
def test(self): |
| 957 |
with self.assertRaises(AssertionError): |
| 958 |
six.assertNotRegex(self, 'test', r'^t') |
| 959 |
|
| 960 |
six.assertNotRegex(self, 'test', r'^a') |
| 961 |
|
| 962 |
TestAssertNotRegex('test').test() |
| 963 |
|
| 964 |
|
| 965 |
def test_assertRaisesRegex(): |
| 966 |
class TestAssertRaisesRegex(unittest.TestCase): |
| 967 |
def test(self): |
| 968 |
with six.assertRaisesRegex(self, AssertionError, '^Foo'): |
| 969 |
raise AssertionError('Foo') |
| 970 |
|
| 971 |
with self.assertRaises(AssertionError): |
| 972 |
with six.assertRaisesRegex(self, AssertionError, r'^Foo'): |
| 973 |
raise AssertionError('Bar') |
| 974 |
|
| 975 |
TestAssertRaisesRegex('test').test() |
| 976 |
|
| 977 |
|
| 978 |
def test_python_2_unicode_compatible(): |
| 979 |
@six.python_2_unicode_compatible |
| 980 |
class MyTest(object): |
| 981 |
def __str__(self): |
| 982 |
return six.u('hello') |
| 983 |
|
| 984 |
def __bytes__(self): |
| 985 |
return six.b('hello') |
| 986 |
|
| 987 |
my_test = MyTest() |
| 988 |
|
| 989 |
if six.PY2: |
| 990 |
assert str(my_test) == six.b("hello") |
| 991 |
assert unicode(my_test) == six.u("hello") |
| 992 |
elif six.PY3: |
| 993 |
assert bytes(my_test) == six.b("hello") |
| 994 |
assert str(my_test) == six.u("hello") |
| 995 |
|
| 996 |
assert getattr(six.moves.builtins, 'bytes', str)(my_test) == six.b("hello") |
| 997 |
|
| 998 |
|
| 999 |
class EnsureTests: |
| 1000 |
|
| 1001 |
# grinning face emoji |
| 1002 |
UNICODE_EMOJI = six.u("\U0001F600") |
| 1003 |
BINARY_EMOJI = b"\xf0\x9f\x98\x80" |
| 1004 |
|
| 1005 |
def test_ensure_binary_raise_type_error(self): |
| 1006 |
with pytest.raises(TypeError): |
| 1007 |
six.ensure_str(8) |
| 1008 |
|
| 1009 |
def test_errors_and_encoding(self): |
| 1010 |
six.ensure_binary(self.UNICODE_EMOJI, encoding='latin-1', errors='ignore') |
| 1011 |
with pytest.raises(UnicodeEncodeError): |
| 1012 |
six.ensure_binary(self.UNICODE_EMOJI, encoding='latin-1', errors='strict') |
| 1013 |
|
| 1014 |
def test_ensure_binary_raise(self): |
| 1015 |
converted_unicode = six.ensure_binary(self.UNICODE_EMOJI, encoding='utf-8', errors='strict') |
| 1016 |
converted_binary = six.ensure_binary(self.BINARY_EMOJI, encoding="utf-8", errors='strict') |
| 1017 |
if six.PY2: |
| 1018 |
# PY2: unicode -> str |
| 1019 |
assert converted_unicode == self.BINARY_EMOJI and isinstance(converted_unicode, str) |
| 1020 |
# PY2: str -> str |
| 1021 |
assert converted_binary == self.BINARY_EMOJI and isinstance(converted_binary, str) |
| 1022 |
else: |
| 1023 |
# PY3: str -> bytes |
| 1024 |
assert converted_unicode == self.BINARY_EMOJI and isinstance(converted_unicode, bytes) |
| 1025 |
# PY3: bytes -> bytes |
| 1026 |
assert converted_binary == self.BINARY_EMOJI and isinstance(converted_binary, bytes) |
| 1027 |
|
| 1028 |
def test_ensure_str(self): |
| 1029 |
converted_unicode = six.ensure_str(self.UNICODE_EMOJI, encoding='utf-8', errors='strict') |
| 1030 |
converted_binary = six.ensure_str(self.BINARY_EMOJI, encoding="utf-8", errors='strict') |
| 1031 |
if six.PY2: |
| 1032 |
# PY2: unicode -> str |
| 1033 |
assert converted_unicode == self.BINARY_EMOJI and isinstance(converted_unicode, str) |
| 1034 |
# PY2: str -> str |
| 1035 |
assert converted_binary == self.BINARY_EMOJI and isinstance(converted_binary, str) |
| 1036 |
else: |
| 1037 |
# PY3: str -> str |
| 1038 |
assert converted_unicode == self.UNICODE_EMOJI and isinstance(converted_unicode, str) |
| 1039 |
# PY3: bytes -> str |
| 1040 |
assert converted_binary == self.UNICODE_EMOJI and isinstance(converted_unicode, str) |
| 1041 |
|
| 1042 |
def test_ensure_text(self): |
| 1043 |
converted_unicode = six.ensure_text(self.UNICODE_EMOJI, encoding='utf-8', errors='strict') |
| 1044 |
converted_binary = six.ensure_text(self.BINARY_EMOJI, encoding="utf-8", errors='strict') |
| 1045 |
if six.PY2: |
| 1046 |
# PY2: unicode -> unicode |
| 1047 |
assert converted_unicode == self.UNICODE_EMOJI and isinstance(converted_unicode, unicode) |
| 1048 |
# PY2: str -> unicode |
| 1049 |
assert converted_binary == self.UNICODE_EMOJI and isinstance(converted_unicode, unicode) |
| 1050 |
else: |
| 1051 |
# PY3: str -> str |
| 1052 |
assert converted_unicode == self.UNICODE_EMOJI and isinstance(converted_unicode, str) |
| 1053 |
# PY3: bytes -> str |
| 1054 |
assert converted_binary == self.UNICODE_EMOJI and isinstance(converted_unicode, str) |