2011-05-21 41 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+,共享緩存將被啓用,所以你可以寫與能力測試在線程之間共享數據庫。

所以,如果你有升級選項,它應該工作。

相關問題