2011-05-21 94 views
7

我正在尝试编写django请求的测试,这可能需要很长时间才能处理,因此可能会与其他请求交错。我的计划是发出长时间运行的请求,并将断言注入可能会暂停的地方。在Django测试交错长时间运行的请求

但想在我的单元测试使用线程似乎并没有很好地工作:

class ThreadTest(test.TestCase): 
    def thread_test(self): 
     def printer(): 
      print models.Daemon.objects.count() 

     d = models.Daemon(url='http://lockss.notadomain:8088') 
     d.save() 
     printer() 
     t = threading.Thread(target=printer) 
     t.start() 
     t.join() 

打印机()调用工程,我所期待的第一次,但后来从一个线程调用时无法找到表格:

1 
Exception in thread Thread-1: 
Traceback (most recent call last): 
    File "/usr/lib/python2.6/threading.py", line 532, in __bootstrap_inner 
    self.run() 
    File "/usr/lib/python2.6/threading.py", line 484, in run 
    self.__target(*self.__args, **self.__kwargs) 
    File "/home/bhayes/lockss-code/hare/lockss-django/autest/tests.py", line 247, in printer 
    print models.Daemon.objects.count() 
    File "/usr/lib/pymodules/python2.6/django/db/models/manager.py", line 120, in count 
    return self.get_query_set().count() 
    File "/usr/lib/pymodules/python2.6/django/db/models/query.py", line 326, in count 
    return self.query.get_count(using=self.db) 
    File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py", line 394, in get_count 
    number = obj.get_aggregation(using=using)[None] 
    File "/usr/lib/pymodules/python2.6/django/db/models/sql/query.py", line 366, in get_aggregation 
    result = query.get_compiler(using).execute_sql(SINGLE) 
    File "/usr/lib/pymodules/python2.6/django/db/models/sql/compiler.py", line 727, in execute_sql 
    cursor.execute(sql, params) 
    File "/usr/lib/pymodules/python2.6/django/db/backends/sqlite3/base.py", line 200, in execute 
    return Database.Cursor.execute(self, query, params) 
DatabaseError: no such table: autest_daemon 

我想了解发生了什么。另外,我想知道是否有更好的策略来测试并行请求。

+1

不确定这是否真的适用于测试,但是您是否考虑过使用celeryd来进行异步处理? – 2011-07-11 20:52:49

+0

杰克可能是正确的,芹菜真的很坚固。 – 2011-07-14 12:37:41

回答

1

你不能在Django中的内存数据库(在这种情况下,sqlite3)使用线程看到这个bug。您的测试可能适用于PostgreSQL或MySQL。

1

正如罗布所说,在问题出现时,SQLite无法做到这一点。然而,随着Django的1.8(见https://docs.djangoproject.com/en/1.8/topics/testing/overview/):

如果使用一个SQLite内存数据库与Python 3.4+和SQLite 3.7.13+,共享缓存将被启用,所以你可以写与能力测试在线程之间共享数据库。

所以,如果你有升级选项,它应该工作。