summaryrefslogtreecommitdiff
path: root/sandbox/test_green_error.py
blob: 71b176f0bbe477aa40bac4ec9d58cc264e912807 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python
"""Test for issue #113: test with error during green processing
"""

DSN = 'dbname=test'

import eventlet.patcher
eventlet.patcher.monkey_patch()

import os
import signal
from time import sleep

import psycopg2
from psycopg2 import extensions
from eventlet.hubs import trampoline


# register a test wait callback that fails if SIGHUP is received

panic = []

def wait_cb(conn):
    """A wait callback useful to allow eventlet to work with Psycopg."""
    while 1:
        if panic:
            raise Exception('whatever')

        state = conn.poll()
        if state == extensions.POLL_OK:
            break
        elif state == extensions.POLL_READ:
            trampoline(conn.fileno(), read=True)
        elif state == extensions.POLL_WRITE:
            trampoline(conn.fileno(), write=True)
        else:
            raise psycopg2.OperationalError(
                "Bad result from poll: %r" % state)

extensions.set_wait_callback(wait_cb)


# SIGHUP handler to inject a fail in the callback

def handler(signum, frame):
    panic.append(True)

signal.signal(signal.SIGHUP, handler)


# Simulate another green thread working

def worker():
    while 1:
        print("I'm working")
        sleep(1)

eventlet.spawn(worker)


# You can unplug the network cable etc. here.
# Kill -HUP will raise an exception in the callback.

print("PID", os.getpid())
conn = psycopg2.connect(DSN)
curs = conn.cursor()
try:
    for i in range(1000):
        curs.execute("select %s, pg_sleep(1)", (i,))
        r = curs.fetchone()
        print("selected", r)

except BaseException, e:
    print("got exception:", e.__class__.__name__, e)

if conn.closed:
    print("the connection is closed")
else:
    conn.rollback()
    curs.execute("select 1")
    print(curs.fetchone())