golang_test.py 54.1 KB
Newer Older
1
# -*- coding: utf-8 -*-
2
# Copyright (C) 2018-2021  Nexedi SA and Contributors.
3
#                          Kirill Smelkov <kirr@nexedi.com>
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#
# This program is free software: you can Use, Study, Modify and Redistribute
# it under the terms of the GNU General Public License version 3, or (at your
# option) any later version, as published by the Free Software Foundation.
#
# You can also Link and Combine this program with other software covered by
# the terms of any of the Free Software licenses or any of the Open Source
# Initiative approved licenses and Convey the resulting work. Corresponding
# source of such a combination shall include the source code for all other
# software used.
#
# This program is distributed WITHOUT ANY WARRANTY; without even the implied
# warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# See COPYING file for full licensing terms.
# See https://www.nexedi.com/licensing for rationale and options.

21 22
from __future__ import print_function, absolute_import

23 24
from golang import go, chan, select, default, nilchan, _PanicError, func, panic, \
        defer, recover, u, b
25
from golang.gcompat import qq
26
from golang import sync
27
from golang.strconv_test import byterange
28 29
from pytest import raises, mark, fail
from _pytest._code import Traceback
30
from os.path import dirname
31
import os, sys, inspect, importlib, traceback, doctest
32
from subprocess import Popen, PIPE
33
import six
34
from six import text_type as unicode
35
from six.moves import range as xrange
36
import gc, weakref, warnings
37
import re
38

39
from golang import _golang_test
40
from golang._golang_test import pywaitBlocked as waitBlocked, pylen_recvq as len_recvq, \
41
        pylen_sendq as len_sendq, pypanicWhenBlocked as panicWhenBlocked
42

43 44 45 46 47 48
# directories
dir_golang   = dirname(__file__)        # .../pygolang/golang
dir_pygolang = dirname(dir_golang)      # .../pygolang
dir_testprog = dir_golang + "/testprog" # .../pygolang/golang/testprog


49
# pyx/c/c++ tests/benchmarks -> {test,bench}_pyx_* in caller's globals.
50 51 52 53
def import_pyx_tests(modpath):
    mod = importlib.import_module(modpath)
    callf = inspect.currentframe().f_back   # caller's frame
    callg = callf.f_globals                 # caller's globals
54
    tbre  = re.compile("(test|bench)_(.+)")
55
    for f in dir(mod):
56 57 58 59 60
        m = tbre.match(f)
        if m is not None:
            kind, name = m.group(1), m.group(2)
            gf = kind + "_pyx_" + name # test_chan_nogil -> test_pyx_chan_nogil

61 62
            # define a python function with gf name (if we use f directly pytest
            # will say "cannot collect 'test_pyx_chan_nogil' because it is not a function")
63 64 65 66 67 68 69 70
            if kind == "test":
                def _(func=getattr(mod, f)):
                    func()
            elif kind == "bench":
                def _(b, func=getattr(mod, f)):
                    func(b)
            else:
                panic("unreachable")
71 72 73 74
            _.__name__ = gf
            callg[gf] = _

import_pyx_tests("golang._golang_test")
Kirill Smelkov's avatar
Kirill Smelkov committed
75 76


77 78 79
# leaked goroutine behaviour check: done in separate process because we need
# to test process termination exit there.
def test_go_leaked():
80
    pyrun([dir_testprog + "/golang_test_goleaked.py"])
81

82
# benchmark go+join a thread/coroutine.
83
# pyx/nogil mirror is in _golang_test.pyx
84 85 86 87 88 89 90 91 92
def bench_go(b):
    done = chan()
    def _():
        done.send(1)

    for i in xrange(b.N):
        go(_)
        done.recv()

93

94 95 96 97 98 99 100
def test_chan():
    # sync: pre-close vs send/recv
    ch = chan()
    ch.close()
    assert ch.recv()    == None
    assert ch.recv_()   == (None, False)
    assert ch.recv_()   == (None, False)
101 102
    with panics("send on closed channel"):  ch.send(0)
    with panics("close of closed channel"): ch.close()
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118

    # sync: send vs recv
    ch = chan()
    def _():
        ch.send(1)
        assert ch.recv() == 2
        ch.close()
    go(_)
    assert ch.recv() == 1
    ch.send(2)
    assert ch.recv_() == (None, False)
    assert ch.recv_() == (None, False)

    # sync: close vs send
    ch = chan()
    def _():
119
        waitBlocked(ch.send)
120 121
        ch.close()
    go(_)
122
    with panics("send on closed channel"):  ch.send(0)
123 124 125 126

    # close vs recv
    ch = chan()
    def _():
127
        waitBlocked(ch.recv)
128 129 130 131 132 133 134
        ch.close()
    go(_)
    assert ch.recv_() == (None, False)

    # sync: close vs multiple recv
    ch = chan()
    done = chan()
135
    mu = sync.Mutex()
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
    s  = set()
    def _():
        assert ch.recv_() == (None, False)
        with mu:
            x = len(s)
            s.add(x)
        done.send(x)
    for i in range(3):
        go(_)
    ch.close()
    for i in range(3):
        done.recv()
    assert s == {0,1,2}

    # buffered
    ch = chan(3)
    done = chan()
    for _ in range(2):
        for i in range(3):
            assert len(ch) == i
            ch.send(i)
            assert len(ch) == i+1
        for i in range(3):
            assert ch.recv_() == (i, True)

    assert len(ch) == 0
    for i in range(3):
        ch.send(i)
    assert len(ch) == 3
    def _():
166
        waitBlocked(ch.send)
167 168 169 170 171 172 173 174 175 176 177 178
        assert ch.recv_() == (0, True)
        done.send('a')
        for i in range(1,4):
            assert ch.recv_() == (i, True)
        assert ch.recv_() == (None, False)
        done.send('b')
    go(_)
    ch.send(3)  # will block without receiver
    assert done.recv() == 'a'
    ch.close()
    assert done.recv() == 'b'

179 180 181 182 183 184 185 186 187 188 189 190 191 192
    # buffered: releases objects in buffer on chan gc
    ch = chan(3)
    class Obj(object): pass
    obj1 = Obj(); w1 = weakref.ref(obj1); assert w1() is obj1
    obj2 = Obj(); w2 = weakref.ref(obj2); assert w2() is obj2
    ch.send(obj1)
    ch.send(obj2)
    del obj1
    del obj2
    gc.collect()
    assert w1() is not None
    assert w2() is not None
    ch = None
    gc.collect()
193 194 195 196 197
    # pypy needs another GC run: pychan does Py_DECREF on buffered objects, but
    # on pypy cpyext objects are not deallocated from Py_DECREF even if
    # ob_refcnt goes to zero - the deallocation is delayed until GC run.
    # see also: http://doc.pypy.org/en/latest/discussion/rawrefcount.html
    gc.collect()
198 199 200
    assert w1() is None
    assert w2() is None

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
# test for buffered chan bug when ch._mu was released too early in _trysend.
def test_chan_buf_send_vs_tryrecv_race():
    # there was a bug when for buffered channel _trysend(ch) was releasing
    # ch._mu before further popping element from ch._dataq. If there was
    # another _tryrecv running concurrently to _trysend, that _tryrecv could
    # pop the element and _trysend would in turn try to pop on empty ch._dataq
    # leading to oops. The test tries to reproduce the following scenario:
    #
    #   T1(recv)          T2(send)                T3(_tryrecv)
    #
    # recv(blocked)
    #
    #                ch.mu.lock
    #                ch.dataq.append(x)
    #                ch.mu.unlock()
    #                                           ch.mu.lock
    #                                           ch.dataq.popleft()
    #
    #                # oopses since T3 already
    #                # popped the value
    #                ch.dataq.popleft()
    ch   = chan(1) # buffered
    done = chan()
    N = 1000

    # T1: recv(blocked)
    def _():
        for i in range(N):
            assert ch.recv() == i
        done.send(1)
    go(_)

    tryrecv_ctl = chan()  # send <-> _tryrecv sync

    # T2: send after recv is blocked -> _trysend succeeds
    def _():
        for i in range(N):
            waitBlocked(ch.recv)        # ch.recv() ^^^ entered ch._recvq
            tryrecv_ctl.send('start')   # signal _tryrecv to start
            ch.send(i)
            assert tryrecv_ctl.recv() == 'done'  # wait _tryrecv to finish
        done.send(1)
    go(_)

    # T3: _tryrecv running in parallel to _trysend
    def _():
        for i in range(N):
            assert tryrecv_ctl.recv() == 'start'
            _, _rx = select(
                    ch.recv,    # 0
                    default,    # 1
            )
            assert (_, _rx) == (1, None)
            tryrecv_ctl.send('done')
        done.send(1)
    go(_)

    for i in range(3):
        done.recv()
260

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
# test for buffered chan bug when ch._mu was released too early in _tryrecv.
def test_chan_buf_recv_vs_tryrecv_race():
    # (see test_chan_buf_send_vs_tryrecv_race for similar problem description)
    #
    #   T1(send)          T2(recv)                T3(_trysend)
    #
    # send(blocked)
    #
    #                ch.mu.lock
    #                ch.dataq.popleft()
    #                send = _dequeWaiter(ch._sendq)
    #                ch.mu.unlock()
    #
    #                                           ch.mu.lock
    #                                           len(ch.dataq) == 0 -> ok to append
    #
    #                                           # erroneously succeeds sending while
    #                                           # it must not
    #                                           ch.dataq.append(x)
    #
    #                ch.dataq.append(send.obj)
    ch   = chan(1) # buffered
    done = chan()
    N = 1000

    # T1: send(blocked)
    def _():
        for i in range(1 + N):
            ch.send(i)
        done.send(1)
    go(_)

    trysend_ctl = chan()  # recv <-> _trysend sync

    # T2: recv after send is blocked -> _tryrecv succeeds
    def _():
        for i in range(N):
            waitBlocked(ch.send)        # ch.send() ^^^ entered ch._sendq
            assert len(ch) == 1         # and 1 element was already buffered
            trysend_ctl.send('start')   # signal _trysend to start
            assert ch.recv() == i
            assert trysend_ctl.recv() == 'done' # wait _trysend to finish
        done.send(1)
    go(_)

    # T3: _trysend running in parallel to _tryrecv
    def _():
        for i in range(N):
            assert trysend_ctl.recv() == 'start'
            _, _rx = select(
                    (ch.send, 'i%d' % i),   # 0
                    default,                # 1
            )
            assert (_, _rx) == (1, None), ('i%d' % i)
            trysend_ctl.send('done')
        done.send(1)
    go(_)

    for i in range(3):
        done.recv()

322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
# send/recv on the same channel in both directions.
# this triggers https://bugs.python.org/issue38106 on MacOS.
def test_chan_sendrecv_2way():
    N = 1000

    ch = chan()
    def _():
        for i in range(N):
            assert ch.recv() == ('hello %d' % i)
            ch.send('world %d' % i)
    go(_)

    for i in range(N):
        ch.send('hello %d' % i)
        assert ch.recv() == ('world %d' % i)

338

339
# benchmark sync chan send/recv.
340
# pyx/nogil mirror is in _golang_test.pyx
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
def bench_chan(b):
    ch   = chan()
    done = chan()
    def _():
        while 1:
            _, ok = ch.recv_()
            if not ok:
                done.close()
                return
    go(_)

    for i in xrange(b.N):
        ch.send(1)
    ch.close()
    done.recv()


358
def test_select():
359 360
    N = 1000 # times to do repeated select/chan or select/select interactions

361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376
    # sync: close vs select(send)
    ch = chan()
    def _():
        waitBlocked(ch.send)
        ch.close()
    go(_)
    with panics("send on closed channel"): select((ch.send, 0))

    # sync: close vs select(recv)
    ch = chan()
    def _():
        waitBlocked(ch.recv)
        ch.close()
    go(_)
    assert select(ch.recv) == (0, None)

377 378
    # non-blocking try send: not ok
    ch = chan()
379 380 381 382 383 384
    for i in range(N):
        _, _rx = select(
                (ch.send, 0),
                default,
        )
        assert (_, _rx) == (1, None)
385 386

    # non-blocking try recv: not ok
387 388 389 390 391 392 393 394 395 396 397 398
    for i in range(N):
        _, _rx = select(
                ch.recv,
                default,
        )
        assert (_, _rx) == (1, None)

        _, _rx = select(
                ch.recv_,
                default,
        )
        assert (_, _rx) == (1, None)
399 400 401 402 403 404 405 406 407 408 409 410 411 412 413

    # non-blocking try send: ok
    ch = chan()
    done = chan()
    def _():
        i = 0
        while 1:
            x = ch.recv()
            if x == 'stop':
                break
            assert x == i
            i += 1
        done.close()
    go(_)

414
    for i in range(N):
415
        waitBlocked(ch.recv)
416 417 418 419 420 421 422 423 424 425 426 427
        _, _rx = select(
                (ch.send, i),
                default,
        )
        assert (_, _rx) == (0, None)
    ch.send('stop')
    done.recv()

    # non-blocking try recv: ok
    ch = chan()
    done = chan()
    def _():
428
        for i in range(N):
429 430 431 432
            ch.send(i)
        done.close()
    go(_)

433
    for i in range(N):
434
        waitBlocked(ch.send)
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
        if i % 2:
            _, _rx = select(
                    ch.recv,
                    default,
            )
            assert (_, _rx) == (0, i)
        else:
            _, _rx = select(
                    ch.recv_,
                    default,
            )
            assert (_, _rx) == (0, (i, True))
    done.recv()


    # blocking 2·send
    ch1 = chan()
    ch2 = chan()
    done = chan()
    def _():
455 456 457 458 459 460
        while 1:
            waitBlocked(ch1.send)
            x = ch1.recv()
            if x == 'stop':
                break
            assert x == 'a'
461 462 463
        done.close()
    go(_)

464 465 466 467 468 469 470
    for i in range(N):
        _, _rx = select(
            (ch1.send, 'a'),
            (ch2.send, 'b'),
        )
        assert (_, _rx) == (0, None)
    ch1.send('stop')
471
    done.recv()
472 473
    assert len_sendq(ch1) == len_recvq(ch1) == 0
    assert len_sendq(ch2) == len_recvq(ch2) == 0
474 475 476 477 478 479 480


    # blocking 2·recv
    ch1 = chan()
    ch2 = chan()
    done = chan()
    def _():
481 482 483
        for i in range(N):
            waitBlocked(ch1.recv)
            ch1.send('a')
484 485 486
        done.close()
    go(_)

487 488 489 490 491 492
    for i in range(N):
        _, _rx = select(
            ch1.recv,
            ch2.recv,
        )
        assert (_, _rx) == (0, 'a')
493
    done.recv()
494 495
    assert len_sendq(ch1) == len_recvq(ch1) == 0
    assert len_sendq(ch2) == len_recvq(ch2) == 0
496 497 498 499 500 501 502


    # blocking send/recv
    ch1 = chan()
    ch2 = chan()
    done = chan()
    def _():
503 504 505 506 507 508
        while 1:
            waitBlocked(ch1.send)
            x = ch1.recv()
            if x == 'stop':
                break
            assert x == 'a'
509 510 511
        done.close()
    go(_)

512 513 514 515 516 517 518
    for i in range(N):
        _, _rx = select(
            (ch1.send, 'a'),
            ch2.recv,
        )
        assert (_, _rx) == (0, None)
    ch1.send('stop')
519
    done.recv()
520 521
    assert len_sendq(ch1) == len_recvq(ch1) == 0
    assert len_sendq(ch2) == len_recvq(ch2) == 0
522 523 524 525 526 527 528


    # blocking recv/send
    ch1 = chan()
    ch2 = chan()
    done = chan()
    def _():
529 530 531
        for i in range(N):
            waitBlocked(ch1.recv)
            ch1.send('a')
532 533 534
        done.close()
    go(_)

535 536 537 538 539 540
    for i in range(N):
        _, _rx = select(
            ch1.recv,
            (ch2.send, 'b'),
        )
        assert (_, _rx) == (0, 'a')
541
    done.recv()
542 543
    assert len_sendq(ch1) == len_recvq(ch1) == 0
    assert len_sendq(ch2) == len_recvq(ch2) == 0
544 545


546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564
    # blocking send + nil channel
    z = nilchan
    for i in range(N):
        ch = chan()
        done = chan()
        def _():
            waitBlocked(ch.send)
            assert ch.recv() == 'c'
            done.close()
        go(_)

        _, _rx = select(
                z.recv,
                (z.send, 0),
                (ch.send, 'c'),
        )

        assert (_, _rx) == (2, None)
        done.recv()
565
        assert len_sendq(ch) == len_recvq(ch) == 0
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584

    # blocking recv + nil channel
    for i in range(N):
        ch = chan()
        done = chan()
        def _():
            waitBlocked(ch.recv)
            ch.send('d')
            done.close()
        go(_)

        _, _rx = select(
                z.recv,
                (z.send, 0),
                ch.recv,
        )

        assert (_, _rx) == (2, 'd')
        done.recv()
585
        assert len_sendq(ch) == len_recvq(ch) == 0
586 587


588 589
    # buffered ping-pong
    ch = chan(1)
590
    for i in range(N):
591 592 593 594 595 596 597 598 599
        _, _rx = select(
            (ch.send, i),
            ch.recv,
        )
        assert _    == (i % 2)
        assert _rx  == (i - 1 if i % 2 else None)


    # select vs select
600
    # channels are recreated on every iteration.
601
    for i in range(N):
602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634
        ch1 = chan()
        ch2 = chan()
        done = chan()
        def _():
            _, _rx = select(
                (ch1.send, 'a'),
                (ch2.send, 'xxx2'),
            )
            assert (_, _rx) == (0, None)

            _, _rx = select(
                (ch1.send, 'yyy2'),
                ch2.recv,
            )
            assert (_, _rx) == (1, 'b')

            done.close()

        go(_)

        _, _rx = select(
            ch1.recv,
            (ch2.send, 'xxx1'),
        )
        assert (_, _rx) == (0, 'a')

        _, _rx = select(
            (ch1.send, 'yyy1'),
            (ch2.send, 'b'),
        )
        assert (_, _rx) == (1, None)

        done.recv()
635 636
        assert len_sendq(ch1) == len_recvq(ch1) == 0
        assert len_sendq(ch2) == len_recvq(ch2) == 0
637 638


639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
    # select vs select
    # channels are shared for all iterations.
    # (this tries to trigger parasitic effects from already performed select)
    ch1 = chan()
    ch2 = chan()
    done = chan()
    def _():
        for i in range(N):
            _, _rx = select(
                (ch1.send, 'a%d' % i),
                (ch2.send, 'xxx2'),
            )
            assert (_, _rx) == (0, None)

            _, _rx = select(
                (ch1.send, 'yyy2'),
                ch2.recv,
            )
            assert (_, _rx) == (1, 'b%d' % i)

        done.close()

    go(_)

    for i in range(N):
        _, _rx = select(
            ch1.recv,
            (ch2.send, 'xxx1'),
        )
        assert (_, _rx) == (0, 'a%d' % i)

        _, _rx = select(
            (ch1.send, 'yyy1'),
            (ch2.send, 'b%d' % i),
        )
        assert (_, _rx) == (1, None)

    done.recv()
677 678
    assert len_sendq(ch1) == len_recvq(ch1) == 0
    assert len_sendq(ch2) == len_recvq(ch2) == 0
679 680


681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720
# verify that select does not leak references to passed objects.
@mark.skipif(not hasattr(sys, 'getrefcount'),   # skipped e.g. on PyPy
             reason="needs sys.getrefcount")
def test_select_refleak():
    ch1 = chan()
    ch2 = chan()
    obj1 = object()
    obj2 = object()
    tx1 = (ch1.send, obj1)
    tx2 = (ch2.send, obj2)

    # normal exit
    gc.collect()
    nref1 = sys.getrefcount(obj1)
    nref2 = sys.getrefcount(obj2)
    _, _rx = select(
        tx1,        # 0
        tx2,        # 1
        default,    # 2
    )
    assert (_, _rx) == (2, None)
    gc.collect()
    assert sys.getrefcount(obj1) == nref1
    gc.collect()
    assert sys.getrefcount(obj1) == nref2

    # abnormal exit
    with raises(AttributeError) as exc:
        select(
            tx1,        # 0
            tx2,        # 1
            'zzz',      # 2 causes pyselect to panic
        )
    assert exc.value.args == ("'str' object has no attribute '__self__'",)
    gc.collect()
    assert sys.getrefcount(obj1) == nref1
    gc.collect()
    assert sys.getrefcount(obj1) == nref2


721
# benchmark sync chan send vs recv on select side.
722
# pyx/nogil mirror is in _golang_test.pyx
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748
def bench_select(b):
    ch1  = chan()
    ch2  = chan()
    done = chan()
    def _():
        while 1:
            _, _rx = select(
                ch1.recv_,   # 0
                ch2.recv_,   # 1
            )
            if _ == 0:
                _, ok = _rx
                if not ok:
                    done.close()
                    return
    go(_)

    _ = (ch1, ch2)
    for i in xrange(b.N):
        ch = _[i%2]
        ch.send(1)

    ch1.close()
    done.recv()


749
def test_blockforever():
750
    with panicWhenBlocked():
751 752 753 754
        _test_blockforever()

def _test_blockforever():
    z = nilchan
755 756
    assert len(z) == 0
    assert repr(z) == "nilchan"
757 758
    with panics("t: blocks forever"): z.send(0)
    with panics("t: blocks forever"): z.recv()
759
    with panics("close of nil channel"): z.close()   # to fully cover nilchan ops
760 761

    # select{} & nil-channel only
762 763 764 765
    with panics("t: blocks forever"): select()
    with panics("t: blocks forever"): select((z.send, 0))
    with panics("t: blocks forever"): select(z.recv)
    with panics("t: blocks forever"): select((z.send, 1), z.recv)
766 767


768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
# verify chan(dtype=X) functionality.
def test_chan_dtype_invalid():
    with raises(TypeError) as exc:
        chan(dtype="BadType")
    assert exc.value.args == ("pychan: invalid dtype: 'BadType'",)

chantypev = [
    # dtype         obj     zero-obj
    ('object',      'abc',  None),
    ('C.structZ',   None,   None),
    ('C.bool',      True,   False),
    ('C.int',       4,      0),
    ('C.double',    3.14,   0.0),
]

@mark.parametrize('dtype,obj,zobj', chantypev)
def test_chan_dtype(dtype, obj, zobj):
    # py -> py  (pysend/pyrecv; buffered)
    ch = chan(1, dtype=dtype)
    ch.send(obj)
    obj2, ok = ch.recv_()
    assert ok == True
    assert type(obj2) is type(obj)
    assert obj2 == obj

    # send with different type - rejected
    for (dtype2, obj2, _) in chantypev:
        if dtype2 == dtype or dtype == "object":
            continue    # X -> X; object accepts *,
        if (dtype2, dtype) == ('C.int', 'C.double'): # int -> double  ok
            continue
        with raises(TypeError) as exc:
            ch.send(obj2)
        # XXX we can implement vvv, but it will potentially hide cause error
        # XXX (or use raise from?)
        #assert exc.value.args == ("type mismatch: expect %s; got %r" % (dtype, obj2),)
        with raises(TypeError) as exc:
            select((ch.send, obj2))

    # py -> py  (pyclose/pyrecv)
    ch.close()
    obj2, ok = ch.recv_()
    assert ok == False
    assert type(obj2) is type(zobj)
    assert obj2 == zobj

    # below tests are for py <-> c interaction
    if dtype == "object":
        return
    ctype = dtype[2:]  # C.int -> int

    ch = chan(dtype=dtype)  # recreate after close; mode=synchronous

    # recv/send/close via C
    def crecv(ch):
        return getattr(_golang_test, "pychan_%s_recv" % ctype)(ch)
    def csend(ch, obj):
        getattr(_golang_test, "pychan_%s_send" % ctype)(ch, obj)
    def cclose(ch):
        getattr(_golang_test, "pychan_%s_close" % ctype)(ch)

    # py -> c  (pysend/crecv)
    rx = chan()
    def _():
        _ = crecv(ch)
        rx.send(_)
    go(_)
    ch.send(obj)
    obj2 = rx.recv()
    assert type(obj2) is type(obj)
    assert obj2 == obj

    # py -> c  (pyselect/crecv)
    rx = chan()
    def _():
        _ = crecv(ch)
        rx.send(_)
    go(_)
    _, _rx = select(
        (ch.send, obj), # 0
    )
    assert (_, _rx) == (0, None)
    obj2 = rx.recv()
    assert type(obj2) is type(obj)
    assert obj2 == obj

    # py -> c  (pyclose/crecv)
    rx = chan()
    def _():
        _ = crecv(ch)
        rx.send(_)
    go(_)
    ch.close()
    obj2 = rx.recv()
    assert type(obj2) is type(zobj)
    assert obj2 == zobj


    ch = chan(dtype=dtype)  # recreate after close

    # py <- c  (pyrecv/csend)
    def _():
        csend(ch, obj)
    go(_)
    obj2 = ch.recv()
    assert type(obj2) is type(obj)
    assert obj2 == obj

    # py <- c  (pyselect/csend)
    def _():
        csend(ch, obj)
    go(_)
    _, _rx = select(
        ch.recv,        # 0
    )
    assert _ == 0
    obj2 = _rx
    assert type(obj2) is type(obj)
    assert obj2 == obj

    # py <- c  (pyrecv/cclose)
    def _():
        cclose(ch)
    go(_)
    obj2 = ch.recv()
    assert type(obj2) is type(zobj)
    assert obj2 == zobj


@mark.parametrize('dtype', [_[0] for _ in chantypev])
def test_chan_dtype_misc(dtype):
    nilch = chan.nil(dtype)

    # nil repr
    if dtype == "object":
        assert repr(nilch) == "nilchan"
    else:
        assert repr(nilch) == ("chan.nil(%r)" % dtype)
906

907 908 909 910 911 912 913
    # optimization: nil[X]() -> always same object
    nilch_ = chan.nil(dtype)
    assert nilch is nilch_
    if dtype == "object":
        assert nilch is nilchan

    assert hash(nilch) == hash(nilchan)
914 915 916 917 918 919
    assert      (nilch == nilch)            # nil[X] == nil[X]
    assert not  (nilch != nilch)
    assert      (nilch == nilchan)          # nil[X] == nil[*]
    assert not  (nilch != nilchan)
    assert      (nilchan == nilch)          # nil[*] == nil[X]
    assert not  (nilchan != nilch)
920 921 922

    # channels can be compared, different channels differ
    assert nilch != None    # just in case
923 924
    ch1 = chan(dtype=dtype)
    ch2 = chan(dtype=dtype)
925
    ch3 = chan()
926 927 928
    assert ch1 != ch2;  assert not (ch1 == ch2);  assert ch1 == ch1; assert not (ch1 != ch1)
    assert ch1 != ch3;  assert not (ch1 == ch3);  assert ch2 == ch2; assert not (ch2 != ch2)
    assert ch2 != ch3;  assert not (ch2 == ch3);  assert ch3 == ch3; assert not (ch3 != ch3)
929 930 931
    assert hash(nilch) != hash(ch1)
    assert hash(nilch) != hash(ch2)
    assert hash(nilch) != hash(ch3)
932 933 934
    assert nilch != ch1;  assert not (nilch == ch1)
    assert nilch != ch2;  assert not (nilch == ch2)
    assert nilch != ch3;  assert not (nilch == ch3)
935

936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972
    # .nil on chan instance     XXX doesn't work (yet ?)
    """
    ch = chan() # non-nil chan object instance
    with raises(AttributeError):
        ch.nil
    """

    # nil[X] vs nil[Y]
    for (dtype2, _, _) in chantypev:
        nilch2 = chan.nil(dtype2)
        # nil[*] stands for untyped nil - it is equal to nil[X] for ∀ X
        if dtype == "object" or dtype2 == "object":
            if dtype != dtype2:
                assert nilch is not nilch2
            assert hash(nilch) == hash(nilch2)
            assert (nilch  == nilch2)   == True
            assert (nilch2 == nilch)    == True
            assert (nilch  != nilch2)   == False
            assert (nilch2 != nilch)    == False
            continue

        # nil[X] == nil[X]
        if dtype == dtype2:
            assert hash(nilch) == hash(nilch2)
            assert (nilch  == nilch2)   == True
            assert (nilch2 == nilch)    == True
            assert (nilch  != nilch2)   == False
            assert (nilch2 != nilch)    == False
            continue

        # nil[X] != nil[Y]
        assert nilch is not nilch2
        assert (nilch  == nilch2)   == False
        assert (nilch2 == nilch)    == False
        assert (nilch  != nilch2)   == True
        assert (nilch2 != nilch)    == True

973

974
def test_func():
975 976
    # test how @func(cls) works
    # this also implicitly tests just @func, since @func(cls) uses that.
977 978 979 980 981

    class MyClass:
        def __init__(self, v):
            self.v = v

982
    zzz = zzz_orig = 'z'    # `@func(MyClass) def zzz` must not override zzz
Kirill Smelkov's avatar
Kirill Smelkov committed
983
    @func(MyClass)
984 985 986
    def zzz(self, v, x=2, **kkkkwww):
        assert self.v == v
        return v + 1
987 988
    assert zzz is zzz_orig
    assert zzz == 'z'
989

990
    mstatic = mstatic_orig = 'mstatic'
991
    @func(MyClass)
992 993 994 995
    @staticmethod
    def mstatic(v):
        assert v == 5
        return v + 1
996 997
    assert mstatic is mstatic_orig
    assert mstatic == 'mstatic'
998

999
    mcls = mcls_orig = 'mcls'
1000
    @func(MyClass)
1001 1002 1003 1004 1005
    @classmethod
    def mcls(cls, v):
        assert cls is MyClass
        assert v == 7
        return v + 1
1006 1007 1008 1009
    assert mcls is mcls_orig
    assert mcls == 'mcls'

    # FIXME undefined var after `@func(cls) def var` should be not set
1010 1011 1012 1013 1014 1015

    obj = MyClass(4)
    assert obj.zzz(4)       == 4 + 1
    assert obj.mstatic(5)   == 5 + 1
    assert obj.mcls(7)      == 7 + 1

1016
    # this tests that @func (used by @func(cls)) preserves decorated function signature
1017
    assert fmtargspec(MyClass.zzz) == '(self, v, x=2, **kkkkwww)'
1018 1019 1020 1021 1022 1023 1024 1025 1026

    assert MyClass.zzz.__module__       == __name__
    assert MyClass.zzz.__name__         == 'zzz'

    assert MyClass.mstatic.__module__   == __name__
    assert MyClass.mstatic.__name__     == 'mstatic'

    assert MyClass.mcls.__module__      == __name__
    assert MyClass.mcls.__name__        == 'mcls'
1027 1028


1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
# @func overhead at def time.
def bench_def(b):
    for i  in xrange(b.N):
        def _(): pass

def bench_func_def(b):
    for i in xrange(b.N):
        @func
        def _(): pass

# @func overhead at call time.
def bench_call(b):
    def _(): pass
    for i in xrange(b.N):
        _()

def bench_func_call(b):
    @func
    def _(): pass
    for i in xrange(b.N):
        _()

1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073

def test_deferrecover():
    # regular defer calls
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        defer(lambda: v.append(2))
        defer(lambda: v.append(3))

    _()
    assert v == [3, 2, 1]

    # defers called even if exception is raised
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        defer(lambda: v.append(2))
        def _(): v.append('ran ok')
        defer(_)
        1/0

1074
    with raises(ZeroDivisionError): _()
1075 1076 1077 1078 1079 1080 1081
    assert v == ['ran ok', 2, 1]

    # defer without @func is caught and properly reported
    v = []
    def nofunc():
        defer(lambda: v.append('xx'))

1082
    with panics("function nofunc uses defer, but not @func"):
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
        nofunc()

    # panic in deferred call - all defers are called
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        defer(lambda: v.append(2))
        defer(lambda: panic(3))
        defer(lambda: v.append(4))

1094
    with panics(3): _()
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130
    assert v == [4, 2, 1]


    # defer + recover
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        def _():
            r = recover()
            assert r == "aaa"
            v.append('recovered ok')
        defer(_)
        defer(lambda: v.append(3))

        panic("aaa")

    _()
    assert v == [3, 'recovered ok', 1]


    # recover + panic in defer
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        defer(lambda: panic(2))
        def _():
            r = recover()
            assert r == "bbb"
            v.append('recovered 1')
        defer(_)
        defer(lambda: v.append(3))

        panic("bbb")

1131
    with panics(2): _()
1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169
    assert v == [3, 'recovered 1', 1]


    # recover + panic in defer + recover
    v = []
    @func
    def _():
        defer(lambda: v.append(1))
        def _():
            r = recover()
            assert r == "ddd"
            v.append('recovered 2')
        defer(_)
        defer(lambda: panic("ddd"))
        def _():
            r = recover()
            assert r == "ccc"
            v.append('recovered 1')
        defer(_)
        defer(lambda: v.append(3))

        panic("ccc")

    _()
    assert v == [3, 'recovered 1', 'recovered 2', 1]


    # ---- recover() -> None ----

    # no exception / not under defer
    assert recover() is None

    # no exception/panic
    @func
    def _():
        def _():
            assert recover() is None
        defer(_)
1170
    _()
1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182

    # not directly called by deferred func
    v = []
    @func
    def _():
        def f():
            assert recover() is None
            v.append('not recovered')
        defer(lambda: f())

        panic("zzz")

1183
    with panics("zzz"): _()
1184 1185 1186
    assert v == ['not recovered']


1187
    # ---- defer in @func(x) ----
1188

1189
    # defer in @func(cls)
1190 1191 1192 1193 1194
    v = []

    class MyClass:
        pass

1195
    @func(MyClass)
1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
    def zzz(self):
        defer(lambda: v.append(1))
        defer(lambda: v.append(2))
        defer(lambda: v.append(3))

    obj = MyClass()
    obj.zzz()
    assert v == [3, 2, 1]


    # defer in std method
    v = []

    class MyClass:
        @func
        def method(self):
            defer(lambda: v.append(1))
            defer(lambda: v.append(2))
            defer(lambda: v.append(4))

    obj = MyClass()
    obj.method()
    assert v == [4, 2, 1]


    # defer in std @staticmethod
    v = []

    class MyClass:
        @func
        @staticmethod
        def mstatic():
            defer(lambda: v.append(1))
            defer(lambda: v.append(2))
            defer(lambda: v.append(5))

    MyClass.mstatic()
    assert v == [5, 2, 1]


    # defer in std @classmethod
    v = []

    class MyClass:
        @func
        @classmethod
        def mcls(cls):
            assert cls is MyClass
            defer(lambda: v.append(1))
            defer(lambda: v.append(2))
            defer(lambda: v.append(7))

    MyClass.mcls()
    assert v == [7, 2, 1]
1250 1251


1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
# verify that defer correctly establishes exception chain (even on py2).
def test_defer_excchain():
    # just @func/raise embeds traceback and adds ø chain
    @func
    def _():
        raise RuntimeError("err")
    with raises(RuntimeError) as exci:
        _()

    e = exci.value
    assert type(e) is RuntimeError
    assert e.args == ("err",)
    assert e.__cause__      is None
    assert e.__context__    is None
    if six.PY3: # .__traceback__ for top-level exception is not set on py2
        assert e.__traceback__  is not None
        tb = Traceback(e.__traceback__)
        assert tb[-1].name == "_"

    # exceptions in deferred calls are chained
    def d1():
        raise RuntimeError("d1: aaa")
1274 1275 1276
    @func
    def d2():   # NOTE regular raise inside @func
        1/0     # which initially sets .__context__ to None
1277
    @func
1278
    def d3():
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288
        # d33->d32->d31 subchain that has to be correctly glued with neighbours as:
        # "d4: bbb" -> d33->d32->d31 -> 1/0
        def d31(): raise RuntimeError("d31")
        def d32(): raise RuntimeError("d32")
        def d33(): raise RuntimeError("d33")
        defer(d33)
        defer(d32)
        defer(d31)
    def d4():
        raise RuntimeError("d4: bbb")
1289 1290 1291

    @func
    def _():
1292
        defer(d4)
1293 1294 1295 1296 1297 1298 1299 1300
        defer(d3)
        defer(d2)
        defer(d1)
        raise RuntimeError("err")

    with raises(RuntimeError) as exci:
        _()

1301 1302 1303 1304 1305
    e4 = exci.value
    assert type(e4) is RuntimeError
    assert e4.args == ("d4: bbb",)
    assert e4.__cause__     is None
    assert e4.__context__   is not None
1306
    if six.PY3: # .__traceback__ of top-level exception
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338
        assert e4.__traceback__ is not None
        tb4 = Traceback(e4.__traceback__)
        assert tb4[-1].name == "d4"

    e33 = e4.__context__
    assert type(e33) is RuntimeError
    assert e33.args == ("d33",)
    assert e33.__cause__        is None
    assert e33.__context__      is not None
    assert e33.__traceback__    is not None
    tb33 = Traceback(e33.__traceback__)
    assert tb33[-1].name == "d33"

    e32 = e33.__context__
    assert type(e32) is RuntimeError
    assert e32.args == ("d32",)
    assert e32.__cause__        is None
    assert e32.__context__      is not None
    assert e32.__traceback__    is not None
    tb32 = Traceback(e32.__traceback__)
    assert tb32[-1].name == "d32"

    e31 = e32.__context__
    assert type(e31) is RuntimeError
    assert e31.args == ("d31",)
    assert e31.__cause__        is None
    assert e31.__context__      is not None
    assert e31.__traceback__    is not None
    tb31 = Traceback(e31.__traceback__)
    assert tb31[-1].name == "d31"

    e2 = e31.__context__
1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364
    assert type(e2) is ZeroDivisionError
    #assert e2.args == ("division by zero",) # text is different in between py23
    assert e2.__cause__     is None
    assert e2.__context__   is not None
    assert e2.__traceback__ is not None
    tb2 = Traceback(e2.__traceback__)
    assert tb2[-1].name == "d2"

    e1 = e2.__context__
    assert type(e1) is RuntimeError
    assert e1.args == ("d1: aaa",)
    assert e1.__cause__     is None
    assert e1.__context__   is not None
    assert e1.__traceback__ is not None
    tb1 = Traceback(e1.__traceback__)
    assert tb1[-1].name == "d1"

    e = e1.__context__
    assert type(e) is RuntimeError
    assert e.args == ("err",)
    assert e.__cause__      is None
    assert e.__context__    is None
    assert e.__traceback__  is not None
    tb = Traceback(e.__traceback__)
    assert tb[-1].name == "_"

1365
# verify that recover breaks exception chain.
1366
@mark.xfail('PyPy' in sys.version and sys.version_info >= (3,) and sys.pypy_version_info < (7,3),
1367
                reason="https://foss.heptapod.net/pypy/pypy/-/issues/3096")
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404
def test_defer_excchain_vs_recover():
    @func
    def _():
        def p1():
            raise RuntimeError(1)
        defer(p1)
        def p2():
            raise RuntimeError(2)
        defer(p2)
        def _():
            r = recover()
            assert r == "aaa"
        defer(_)
        defer(lambda: panic("aaa"))

    with raises(RuntimeError) as exci:
        _()

    e1 = exci.value
    assert type(e1) is RuntimeError
    assert e1.args == (1,)
    assert e1.__cause__     is None
    assert e1.__context__   is not None
    if six.PY3: # .__traceback__ of top-level exception
        assert e1.__traceback__ is not None
        tb1 = Traceback(e1.__traceback__)
        assert tb1[-1].name == "p1"

    e2 = e1.__context__
    assert type(e2) is RuntimeError
    assert e2.args == (2,)
    assert e2.__cause__     is None
    assert e2.__context__   is None         # not chained to panic
    assert e2.__traceback__ is not None
    tb2 = Traceback(e2.__traceback__)
    assert tb2[-1].name == "p2"

1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505
# verify that recover returns exception with .__traceback__ and excchain context set (even on py2).
def test_recover_traceback_and_excchain():
    # raise -> recover
    @func
    def f1():
        def r1():
            e = recover()
            assert e is not None
            assert type(e) is RuntimeError
            assert e.args == ("qqq",)
            assert e.__cause__    is None
            assert e.__context__  is None
            assert e.__suppress_context__ == False
            assert e.__traceback__ is not None
            tb = Traceback(e.__traceback__)
            assert tb[-1].name == "p1"
            assert tb[-2].name == "p2"
            assert tb[-3].name == "p3"
            assert tb[-4].name == "f1"
            # [-5] == _func._
        defer(r1)

        def p1(): raise RuntimeError("qqq")
        def p2(): p1()
        def p3(): p2()
        p3()
    f1()

    # raise -> defer(raise2) -> recover
    @func
    def f2():
        def r2():
            e2 = recover()
            assert e2 is not None
            assert type(e2) is RuntimeError
            assert e2.args == ("epp2",)
            assert e2.__cause__     is None
            assert e2.__context__   is not None
            assert e2.__suppress_context__ == False
            assert e2.__traceback__ is not None
            t2 = Traceback(e2.__traceback__)
            assert t2[-1].name == "pp2"
            # [-2] == _GoFrame.__exit__

            e1 = e2.__context__
            assert type(e1) is RuntimeError
            assert e1.args == ("epp1",)
            assert e1.__cause__     is None
            assert e1.__context__   is None
            assert e1.__suppress_context__ == False
            assert e1.__traceback__ is not None
            t1 = Traceback(e1.__traceback__)
            assert t1[-1].name == "pp1"
            assert t1[-2].name == "f2"
            # [-3] == _func._
        defer(r2)

        def pp2(): raise RuntimeError("epp2")
        defer(pp2)

        def pp1(): raise RuntimeError("epp1")
        pp1()
    f2()

    # raise -> recover -> wrap+reraise
    @func
    def f3():
        def r3():
            e1 = recover()
            assert e1 is not None
            e2 = RuntimeError("bad2")
            e2.__context__  = e1
            raise e2
        defer(r3)

        def bad1(): raise RuntimeError("bad1")
        bad1()

    with raises(RuntimeError) as exci:
        f3()

    e2 = exci.value
    assert type(e2) is RuntimeError
    assert e2.args == ("bad2",)
    assert e2.__cause__     is None
    assert e2.__context__   is not None
    if six.PY3: # .__traceback__ for top-level exception is not set on py2
        assert e2.__traceback__ is not None
        t2 = Traceback(e2.__traceback__)
        assert t2[-1].name == "r3"
    e1 = e2.__context__
    assert type(e1) is RuntimeError
    assert e1.args == ("bad1",)
    assert e1.__cause__     is None
    assert e1.__context__   is None
    assert e1.__traceback__ is not None
    t1 = Traceback(e1.__traceback__)
    assert t1[-1].name == "bad1"
    assert t1[-2].name == "f3"


1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
# verify that traceback.{print_exception,format_exception} work on chained
# exception correctly.
def test_defer_excchain_traceback():
    # tbstr returns traceback that would be printed for exception e.
    def tbstr(e):
        fout_print = six.StringIO()
        traceback.print_exception(type(e), e, e.__traceback__, file=fout_print)
        lout_format = traceback.format_exception(type(e), e, e.__traceback__)
        out_print  = fout_print.getvalue()
        out_format = "".join(lout_format)
        assert out_print == out_format
        return out_print

    # raise without @func/defer - must be printed correctly
    # (we patch traceback.print_exception & co on py2)
    def alpha():
        def beta():
            raise RuntimeError("gamma")
        beta()

    with raises(RuntimeError) as exci:
        alpha()
    e = exci.value
    if not hasattr(e, '__traceback__'): # py2
        e.__traceback__ = exci.tb

    assertDoc("""\
Traceback (most recent call last):
  File "PYGOLANG/golang/golang_test.py", line ..., in test_defer_excchain_traceback
    alpha()
  File "PYGOLANG/golang/golang_test.py", line ..., in alpha
    beta()
  File "PYGOLANG/golang/golang_test.py", line ..., in beta
    raise RuntimeError("gamma")
RuntimeError: gamma
""", tbstr(e))


    # raise in @func/chained defer
    @func
    def caller():
        def q1():
            raise RuntimeError("aaa")
        defer(q1)
        def q2():
            raise RuntimeError("bbb")
        defer(q2)
        raise RuntimeError("ccc")

    with raises(RuntimeError) as exci:
        caller()
    e = exci.value
    if not hasattr(e, '__traceback__'): # py2
        e.__traceback__ = exci.tb

    assertDoc("""\
Traceback (most recent call last):
  File "PYGOLANG/golang/__init__.py", line ..., in _
    return f(*argv, **kw)
  File "PYGOLANG/golang/golang_test.py", line ..., in caller
    raise RuntimeError("ccc")
RuntimeError: ccc

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/golang_test.py", line ..., in q2
    raise RuntimeError("bbb")
RuntimeError: bbb

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "PYGOLANG/golang/golang_test.py", line ..., in test_defer_excchain_traceback
    caller()
  ...
  File "PYGOLANG/golang/__init__.py", line ..., in _
    return f(*argv, **kw)
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/golang_test.py", line ..., in q1
    raise RuntimeError("aaa")
RuntimeError: aaa
""", tbstr(e))

    e.__suppress_context__ = True
    assertDoc("""\
Traceback (most recent call last):
  File "PYGOLANG/golang/golang_test.py", line ..., in test_defer_excchain_traceback
    caller()
  ...
  File "PYGOLANG/golang/__init__.py", line ..., in _
    return f(*argv, **kw)
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/golang_test.py", line ..., in q1
    raise RuntimeError("aaa")
RuntimeError: aaa
""", tbstr(e))

    e.__cause__ = e.__context__
    assertDoc("""\
Traceback (most recent call last):
  File "PYGOLANG/golang/__init__.py", line ..., in _
    return f(*argv, **kw)
  File "PYGOLANG/golang/golang_test.py", line ..., in caller
    raise RuntimeError("ccc")
RuntimeError: ccc

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/golang_test.py", line ..., in q2
    raise RuntimeError("bbb")
RuntimeError: bbb

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "PYGOLANG/golang/golang_test.py", line ..., in test_defer_excchain_traceback
    caller()
  ...
  File "PYGOLANG/golang/__init__.py", line ..., in _
    return f(*argv, **kw)
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/__init__.py", line ..., in __exit__
    d()
  File "PYGOLANG/golang/golang_test.py", line ..., in q1
    raise RuntimeError("aaa")
RuntimeError: aaa
""", tbstr(e))


# verify that dump of unhandled chained exception traceback works correctly (even on py2).
def test_defer_excchain_dump():
    # run golang_test_defer_excchain.py and verify its output via doctest.
1651
    tbok = readfile(dir_testprog + "/golang_test_defer_excchain.txt")
1652 1653
    retcode, stdout, stderr = _pyrun(["golang_test_defer_excchain.py"],
                                cwd=dir_testprog, stdout=PIPE, stderr=PIPE)
1654
    assert retcode != 0, (stdout, stderr)
1655 1656 1657
    assert stdout == b""
    assertDoc(tbok, stderr)

1658 1659 1660 1661 1662
# ----//---- (ipython)
def test_defer_excchain_dump_ipython():
    tbok = readfile(dir_testprog + "/golang_test_defer_excchain.txt-ipython")
    retcode, stdout, stderr = _pyrun(["-m", "IPython", "--quick", "--colors=NoColor",
                                "-m", "golang_test_defer_excchain"],
1663
                                envadj={"COLUMNS": "80"}, # force ipython5 avoid thinking termwidth=0
1664
                                cwd=dir_testprog, stdout=PIPE, stderr=PIPE)
1665
    assert retcode == 0, (stdout, stderr)
1666 1667 1668 1669 1670 1671 1672 1673
    # ipython5 uses .pyc for filenames instead of .py
    stdout = re.sub(br'\.pyc\b', b'.py', stdout) # normalize .pyc -> .py
    assertDoc(tbok, stdout)
    assert b"Unknown failure executing module: <golang_test_defer_excchain>" in stderr

# ----//---- (pytest)
def test_defer_excchain_dump_pytest():
    tbok = readfile(dir_testprog + "/golang_test_defer_excchain.txt-pytest")
1674 1675 1676 1677
    retcode, stdout, stderr = _pyrun([
                                # don't let pytest emit internal deprecation warnings to stderr
                                "-W", "ignore::DeprecationWarning",
                                "-m", "pytest", "-o", "python_functions=main",
1678 1679
                                "--tb=short", "golang_test_defer_excchain.py"],
                                cwd=dir_testprog, stdout=PIPE, stderr=PIPE)
1680
    assert retcode != 0, (stdout, stderr)
1681 1682 1683
    assert stderr == b""
    assertDoc(tbok, stdout)

1684

1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704
# defer overhead.
def bench_try_finally(b):
    def fin(): pass
    def _():
        try:
            pass
        finally:
            fin()

    for i in xrange(b.N):
        _()

def bench_defer(b):
    def fin(): pass
    @func
    def _():
        defer(fin)

    for i in xrange(b.N):
        _()
1705 1706


1707 1708 1709
# test_error lives in errors_test.py


1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
# verify b, u
def test_strings():
    testv = (
        # bytes          <->            unicode
        (b'',                           u''),
        (b'hello',                      u'hello'),
        (b'hello\nworld',               u'hello\nworld'),
        (b'\xd0\xbc\xd0\xb8\xd1\x80',   u'мир'),

        # invalid utf-8
        (b'\xd0',                       u'\udcd0'),
        (b'a\xd0b',                     u'a\udcd0b'),
        # invalid utf-8 with byte < 0x80
        (b'\xe2\x28\xa1',               u'\udce2(\udca1'),

        # more invalid utf-8
        # https://stackoverflow.com/questions/1301402/example-invalid-utf8-string
        (b"\xc3\x28",                   u'\udcc3('),        # Invalid 2 Octet Sequence
        (b"\xa0\xa1",                   u'\udca0\udca1'),   # Invalid Sequence Identifier
        (b"\xe2\x82\xa1",               u'\u20a1'),         # Valid 3 Octet Sequence '₡'
        (b"\xe2\x28\xa1",               u'\udce2(\udca1'),  # Invalid 3 Octet Sequence (in 2nd Octet)
        (b"\xe2\x82\x28",               u'\udce2\udc82('),  # Invalid 3 Octet Sequence (in 3rd Octet)
        (b"\xf0\x90\x8c\xbc",           u'\U0001033c'),     # Valid 4 Octet Sequence '𐌼'
        (b"\xf0\x28\x8c\xbc",           u'\udcf0(\udc8c\udcbc'), # Invalid 4 Octet Sequence (in 2nd Octet)
        (b"\xf0\x90\x28\xbc",           u'\udcf0\udc90(\udcbc'), # Invalid 4 Octet Sequence (in 3rd Octet)
        (b"\xf0\x28\x8c\x28",           u'\udcf0(\udc8c('), # Invalid 4 Octet Sequence (in 4th Octet)
        (b"\xf8\xa1\xa1\xa1\xa1",                           # Valid 5 Octet Sequence (but not Unicode!)
                                        u'\udcf8\udca1\udca1\udca1\udca1'),
        (b"\xfc\xa1\xa1\xa1\xa1\xa1",                       # Valid 6 Octet Sequence (but not Unicode!)
                                        u'\udcfc\udca1\udca1\udca1\udca1\udca1'),

        # surrogate
        (b'\xed\xa0\x80',               u'\udced\udca0\udc80'),

        # x00 - x1f
        (byterange(0,32),
         u"\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" +
         u"\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"),

        # non-printable utf-8
        (b'\x7f\xc2\x80\xc2\x81\xc2\x82\xc2\x83\xc2\x84\xc2\x85\xc2\x86\xc2\x87',
                                        u"\u007f\u0080\u0081\u0082\u0083\u0084\u0085\u0086\u0087"),
1752 1753 1754 1755

        # some characters with U >= 0x10000
        (b'\xf0\x9f\x99\x8f',           u'\U0001f64f'),    # 🙏
        (b'\xf0\x9f\x9a\x80',           u'\U0001f680'),    # 🚀
1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
    )

    for tbytes, tunicode in testv:
        assert b(tbytes)   == tbytes
        assert u(tunicode) == tunicode

        assert b(tunicode) == tbytes
        assert u(tbytes)   == tunicode

        assert b(u(tbytes))     == tbytes
        assert u(b(tunicode))   == tunicode


    # invalid types
    with raises(TypeError): b(1)
    with raises(TypeError): u(1)
    with raises(TypeError): b(object())
    with raises(TypeError): u(object())

    # TODO also handle bytearray?

1777 1778 1779 1780 1781 1782 1783 1784 1785 1786
    # b(b(·)) = identity
    _ = b(u'миру мир 123')
    assert isinstance(_, bytes)
    assert b(_) is _

    # u(u(·)) = identity
    _ = u(u'мир труд май')
    assert isinstance(_, unicode)
    assert u(_) is _

1787

1788 1789 1790 1791 1792 1793 1794
def test_qq():
    # NOTE qq is also tested as part of strconv.quote

    # qq(any) returns string type
    assert isinstance(qq(b('мир')), str)    # qq(b) -> str (bytes·py2, unicode·py3)
    assert isinstance(qq( u'мир'),  str)    # qq(u) -> str (bytes·py2, unicode·py3)

1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806
    # however what qq returns can be mixed with both unicode and bytes
    assert b'hello %s !' % qq(b('мир')) == b('hello "мир" !')   # b % qq(b)
    assert b'hello %s !' % qq(u('мир')) == b('hello "мир" !')   # b % qq(u) -> b
    assert u'hello %s !' % qq(u('мир')) == u('hello "мир" !')   # u % qq(u)
    assert u'hello %s !' % qq(b('мир')) ==  u'hello "мир" !'    # u % qq(b) -> u

    # custom attributes cannot be injected to what qq returns
    x = qq('мир')
    if not ('PyPy' in sys.version): # https://foss.heptapod.net/pypy/pypy/issues/2763
        with raises(AttributeError):
            x.hello = 1

1807

1808 1809
# ---- misc ----

1810 1811 1812
# _pyrun runs `sys.executable argv... <stdin`.
# it returns exit code, stdout and stderr.
def _pyrun(argv, stdin=None, stdout=None, stderr=None, **kw):   # -> retcode, stdout, stderr
1813 1814
    pyexe = kw.pop('pyexe', sys.executable)
    argv  = [pyexe] + argv
1815 1816 1817 1818

    # adjust $PYTHONPATH to point to pygolang. This makes sure that external
    # script will succeed on `import golang` when running in-tree.
    kw = kw.copy()
1819
    pathv = [dir_pygolang]
1820
    env = kw.pop('env', os.environ.copy())
1821 1822
    envadj = kw.pop('envadj', {})
    env.update(envadj)
1823 1824
    envpath = env.get('PYTHONPATH')
    if envpath is not None:
1825
        pathv.extend(envpath.split(os.pathsep))
1826
    env['PYTHONPATH'] = os.pathsep.join(pathv)
1827 1828

    p = Popen(argv, stdin=(PIPE if stdin else None), stdout=stdout, stderr=stderr, env=env, **kw)
1829
    stdout, stderr = p.communicate(stdin)
1830 1831 1832 1833 1834 1835 1836
    return p.returncode, stdout, stderr

# pyrun runs `sys.executable argv... <stdin`.
# it raises exception if ran command fails.
def pyrun(argv, stdin=None, stdout=None, stderr=None, **kw):
    retcode, stdout, stderr = _pyrun(argv, stdin=stdin, stdout=stdout, stderr=stderr, **kw)
    if retcode:
1837 1838 1839
        raise RuntimeError(' '.join(argv) + '\n' + (stderr and str(stderr) or '(failed)'))
    return stdout

1840
# pyout runs `sys.executable argv... <stdin` and returns its output.
1841
# it raises exception if ran command fails.
1842 1843 1844
def pyout(argv, stdin=None, stdout=PIPE, stderr=None, **kw):
    return pyrun(argv, stdin=stdin, stdout=stdout, stderr=stderr, **kw)

1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
# panics is similar to pytest.raises and asserts that wrapped code panics with arg.
class panics:
    def __init__(self, arg):
        self.arg = arg

    def __enter__(self):
        self.raises = raises(_PanicError)
        self.exc_info = self.raises.__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        ok = self.raises.__exit__(exc_type, exc_val, exc_tb)
        if not ok:
            return ok
        # _PanicError raised - let's check panic argument
        assert self.exc_info.value.args == (self.arg,)
        return ok

def test_panics():
    # no panic -> "did not raise"
    with raises(raises.Exception, match="DID NOT RAISE"):
        with panics(""):
            pass

    # raise different type -> exception propagates
    with raises(RuntimeError, match="hello world"):
        with panics(""):
            raise RuntimeError("hello world")

    # panic with different argument
    with raises(AssertionError, match=r"assert \('bbb',\) == \('aaa',\)"):
        with panics("aaa"):
            panic("bbb")

    # panic with expected argument
    with panics(123):
        panic(123)
1881 1882 1883 1884 1885 1886 1887

# assertDoc asserts that want == got via doctest.
#
# in want:
# - PYGOLANG means real pygolang prefix
# - empty lines are changed to <BLANKLINE>
def assertDoc(want, got):
1888 1889
    want = u(want)
    got  = u(got)
1890 1891

    # normalize got to PYGOLANG
1892 1893 1894
    udir_pygolang = abbrev_home(dir_pygolang)    # /home/x/.../pygolang -> ~/.../pygolang
    got = got.replace(dir_pygolang,  "PYGOLANG") # /home/x/.../pygolang -> PYGOLANG
    got = got.replace(udir_pygolang, "PYGOLANG") # ~/.../pygolang       -> PYGOLANG
1895

1896 1897 1898 1899 1900 1901
    # want: process conditionals
    # PY39(...) -> ... if py39 else ø
    py39 = sys.version_info >= (3, 9)
    want = re.sub(r"PY39\((.*)\)", r"\1" if py39 else "", want)

    # want: ^$ -> <BLANKLINE>
1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912
    while "\n\n" in want:
        want = want.replace("\n\n", "\n<BLANKLINE>\n")

    X = doctest.OutputChecker()
    if not X.check_output(want, got, doctest.ELLIPSIS):
        # output_difference wants Example object with .want attr
        class Ex: pass
        _ = Ex()
        _.want = want
        fail("not equal:\n" + X.output_difference(_, got,
                    doctest.ELLIPSIS | doctest.REPORT_UDIFF))
1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928


# fmtargspec returns formatted arguments for function f.
#
# For example:
#   def f(x, y=3):
#       ...
#   fmtargspec(f) -> '(x, y=3)'
def fmtargspec(f): # -> str
    with warnings.catch_warnings():
        warnings.simplefilter('ignore', DeprecationWarning)
        return inspect.formatargspec(*inspect.getargspec(f))

def test_fmtargspec():
    def f(x, y=3, z=4, *argv, **kw): pass
    assert fmtargspec(f) == '(x, y=3, z=4, *argv, **kw)'
1929 1930 1931 1932 1933 1934


# readfile returns content of file @path.
def readfile(path):
    with open(path, "r") as f:
        return f.read()
1935 1936 1937 1938 1939 1940 1941 1942 1943

# abbrev_home returns path with user home prefix abbreviated with ~.
def abbrev_home(path):
    home = os.path.expanduser('~')
    if path == home:
        return '~'
    if path.startswith(home+'/'):
        return '~'+path[len(home):]
    return path