バージョン
python 3.6.4
django 2.0.3
以下のテストは成功するような気がするけど失敗する
class Test(TestCase):
def threadmain(self):
self.assertTrue(Foo.objects.all().count()>0)
def test(self):
#オブジェクトを作成する
Foo.objects.create()
th = Thread(target=self.threadmain)
th.start()
th.join()
self.assertTrue(Foo.objects.all().count()>0)
結果
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
........................................................Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/local/lib/python3.6/threading.py", line 916, in _bootstrap_inner
self.run()
File "/usr/local/lib/python3.6/threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
File "/mnt/c/prj/sao/sao/tests.py", line 1414, in threadmain
self.assertTrue(Foo.objects.all().count()>0)
File "/usr/local/lib/python3.6/unittest/case.py", line 682, in assertTrue
raise self.failureException(msg)
AssertionError: False is not true
.....................................
Ran 93 tests in 3.652s
OK
Destroying test database for alias 'default'...
対処
TransactionTestCaseを継承する
class Test(TransactionTestCase):
def threadmain(self):
self.assertTrue(Foo.objects.all().count()>0)
def test(self):
#オブジェクトを作成する
Foo.objects.create()
th = Thread(target=self.threadmain)
th.start()
th.join()
self.assertTrue(Foo.objects.all().count()>0)
結果
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
.............................................................................................
Ran 93 tests in 4.101s
OK
Destroying test database for alias 'default'...