summaryrefslogtreecommitdiff
path: root/tests/othertests/thread_isolation.py
blob: bacbf0341ca6e9a1908b6469b5e18dc65c9b72c0 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# tests that db settings can be different in different threads
#
#
#    What's going on here:
#
#    Simulating multiple web requests in a threaded environment, one in
#    which settings are different for each request. So we replace
#    django.conf.settings with a thread local, with different
#    configurations in each thread, and then fire off three
#    simultaneous requests (using a condition to sync them up), and
#    test that each thread sees its own settings and the models in each
#    thread attempt to connect to the correct database as per their
#    settings.
#


import copy
import os
import sys
import threading
from thread import get_ident

from django import conf
from django.core.handlers.wsgi import WSGIHandler
from django.db import models, model_connection_name, _default, connection, \
     connections
from django.http import HttpResponse

try:
    # Only exists in Python 2.4+
    from threading import local
except ImportError:
    # Import copy of _thread_local.py from Python 2.4
    from django.utils._threading_local import local

# state holder
S = {}

# models
class MQ(models.Model):
    val = models.CharField(maxlength=10)
    class Meta:
        app_label = 'ti'


class MX(models.Model):
    val = models.CharField(maxlength=10)
    class Meta:
        app_label = 'ti'

        
class MY(models.Model):
    val = models.CharField(maxlength=10)
    class Meta:
        app_label = 'ti'

# eventused to synchronize threads so we can be sure they are running
# together
ev = threading.Event()


def test_one(path, request):
    """Start out with settings as originally configured"""
    from django.conf import settings
    debug("test_one: %s", settings.OTHER_DATABASES)

    assert model_connection_name(MQ) == _default
    assert model_connection_name(MX) == 'django_test_db_a', \
           "%s != 'django_test_db_a'" % model_connection_name(MX)
    assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
           settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
    assert model_connection_name(MY) == 'django_test_db_b'
    assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
           settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'], \
           "%s != %s" % \
           (MY._default_manager.db.connection.settings.DATABASE_NAME,
            settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'])
    assert MQ._default_manager.db.connection is \
           connections[_default].connection        
    assert MQ._default_manager.db.connection.settings.DATABASE_NAME == \
           settings.DATABASE_NAME
    assert connection.settings.DATABASE_NAME ==  settings.DATABASE_NAME


def test_two(path, request):
    """Between the first and second requests, settings change to assign
    model MY to a different connection
    """
    from django.conf import settings
    debug("test_two: %s", settings.OTHER_DATABASES)

    try:
        assert model_connection_name(MQ) == _default
        assert model_connection_name(MX) == 'django_test_db_a'
        assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
               settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']
        assert model_connection_name(MY) == _default
        assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
               settings.DATABASE_NAME, "%s != %s" % \
               (MY._default_manager.db.connection.settings.DATABASE_NAME,
                settings.DATABASE_NAME)
        assert MQ._default_manager.db.connection is \
           connections[_default].connection        
        assert MQ._default_manager.db.connection.settings.DATABASE_NAME == \
               settings.DATABASE_NAME
        assert connection.settings.DATABASE_NAME == settings.DATABASE_NAME
    except:
        S.setdefault('errors',[]).append(sys.exc_info())


def test_three(path, request):
    """Between the 2nd and 3rd requests, the settings at the names in
    OTHER_DATABASES have changed.
    """
    from django.conf import settings
    debug("3 %s: %s", get_ident(), settings.OTHER_DATABASES)
    debug("3 %s: default: %s", get_ident(), settings.DATABASE_NAME)
    debug("3 %s: conn: %s", get_ident(), connection.settings.DATABASE_NAME)
    
    try:
        assert model_connection_name(MQ) == _default
        assert model_connection_name(MX) == 'django_test_db_b'
        assert MX._default_manager.db.connection.settings.DATABASE_NAME == \
               settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'],\
               "%s != %s" % \
               (MX._default_manager.db.connection.settings.DATABASE_NAME,
                settings.OTHER_DATABASES['django_test_db_b']['DATABASE_NAME'])
        assert model_connection_name(MY) == 'django_test_db_a'
        assert MY._default_manager.db.connection.settings.DATABASE_NAME == \
               settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'],\
               "%s != %s" % \
               (MY._default_manager.db.connection.settings.DATABASE_NAME,
                settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'])
        assert MQ._default_manager.db.connection is \
           connections[_default].connection
        assert connection.settings.DATABASE_NAME == \
               settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'],\
               "%s != %s" % \
               (connection.settings.DATABASE_NAME,
                settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME'])
    except:
        S.setdefault('errors',[]).append(sys.exc_info())
        
    

# helpers
def thread_two(func, *arg):
    def start():
        from django.conf import settings
        for attr in [ a for a in dir(S['base_settings']) if a == a.upper() ]:
            setattr(settings, attr,
                    copy.deepcopy(getattr(S['base_settings'], attr)))
        
        settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = []
        debug("t2 waiting")
        ev.wait(2.0)
        func(*arg)
        debug("t2 complete")
    t2 = threading.Thread(target=start)
    t2.start()
    return t2


def thread_three(func, *arg):
    def start():
        from django.conf import settings
        for attr in [ a for a in dir(S['base_settings']) if a == a.upper() ]:
            setattr(settings, attr,
                    copy.deepcopy(getattr(S['base_settings'], attr)))
            
        settings.OTHER_DATABASES['django_test_db_b']['MODELS'] = ['ti.MY']
        settings.OTHER_DATABASES['django_test_db_b'], \
            settings.OTHER_DATABASES['django_test_db_a'] = \
            settings.OTHER_DATABASES['django_test_db_a'], \
            settings.OTHER_DATABASES['django_test_db_b']

        settings.DATABASE_NAME = \
            settings.OTHER_DATABASES['django_test_db_a']['DATABASE_NAME']

        # we just manually changed settings, so reset the default
        # connection (normally this isn't needed

        debug("3 %s: start: default: %s", get_ident(), settings.DATABASE_NAME)
        debug("3 %s: start: conn: %s", get_ident(),
              connection.settings.DATABASE_NAME)
        
        debug("t3 waiting")
        ev.wait(2.0)
        func(*arg)
        debug("t3 complete")
    t3 = threading.Thread(target=start)
    t3.start()
    return t3
    

class MockHandler(WSGIHandler):

    def __init__(self, test):
        self.test = test
        super(MockHandler, self).__init__()
        
    def get_response(self, path, request):
        # debug("mock handler answering %s, %s", path, request)
        return HttpResponse(self.test(path, request))
        

def pr(*arg):
    if S['verbosity'] >= 1:
        msg, arg = arg[0], arg[1:]
        print msg % arg


def debug(*arg):
    if S['verbosity'] >= 2:
        msg, arg = arg[0], arg[1:]
        print msg % arg


def setup():
    debug("setup")
    S['settings'] = copy.deepcopy(conf.settings)
    S['base_settings'] = copy.deepcopy(conf.settings)
    S['base_settings'].OTHER_DATABASES['django_test_db_a']['MODELS'] = \
        ['ti.MX']
    S['base_settings'].OTHER_DATABASES['django_test_db_b']['MODELS'] = \
        ['ti.MY']
    
    conf.settings = local()
    for attr in [ a for a in dir(S['base_settings']) if a == a.upper() ]:
        setattr(conf.settings, attr,
                copy.deepcopy(getattr(S['base_settings'], attr)))

    conf.settings.__module__ = S['settings'].__module__
    debug("Setup: %s", conf.settings.OTHER_DATABASES)

    
def teardown():
    debug("teardown")
    conf.settings = S['settings']


def start_response(code, headers):
    debug("start response: %s %s", code, headers)
    pass


def main():
    debug("running tests")

    env = os.environ.copy()
    env['PATH_INFO'] = '/'
    env['REQUEST_METHOD'] = 'GET'
    
    t2 = thread_two(MockHandler(test_two), env, start_response)
    t3 = thread_three(MockHandler(test_three), env, start_response)
    
    try:
        ev.set()
        MockHandler(test_one)(env, start_response)
    finally:
        t2.join()
        t3.join()
        err = S.get('errors', [])
        if err:
            import traceback        
            for e in err:
                traceback.print_exception(*e)
                raise AssertionError("%s thread%s failed" %
                                     (len(err), len(err) > 1 and 's' or ''))
    
def run_tests(verbosity=0):
    S['verbosity'] = verbosity
    
    setup()
    try:
        main()
    finally:
        teardown()

        
if __name__ == '__main__':
    from django.conf import settings
    
    settings.DATABASE_NAME = ':memory:'
    print "MAIN start! ", connection.settings.DATABASE_NAME
    connection.cursor()
    run_tests(2)