I used ThreadPoolExecutor in my API. in the test case, I generated a Movie instance and saved it in the database (PostgreSQL). I printed movie count in the test case, API, and thread pool function. why in the thread pool return an empty queryset?
view.py:
def movie_count():
print(Movie.objects.count(), "movie count in the thread")
class MovieListView(APIView):
renderer_classes = (
render.CamelCaseJSONRenderer,
renderers.BrowsableAPIRenderer,
)
def get(self, request, key, format=None):
print(Movie.objects.count(), "movie count before the thread")
with ThreadPoolExecutor(1) as executor:
bookmarked_future = executor.submit(movie_count)
bookmarked_future.result()
return Response({})
test.py
def test_mock_function(self):
Movie.objects.create(
title="Title"
)
print(Movie.objects.count(), "movie count in the test")
url = reverse('video_api:list', args=('tops',))
self.client.get(url, format='json', data={'limit': 30})
result:
1 movie counts in the test
1 movie count before the thread
0 movie count in the thread
CodePudding user response:
I found the answer.
Difference between TestCase and TransactionTestCase classes in django test
the APITestCase wraps the tests with 2 atomic() blocks, one for the whole test class and one for each test within the class. This essentially stops tests from altering the database for other tests as the transactions are rolled back at the end of each test. By having this second atomic() block around the whole test class, specific database transaction behaviour can be hard to test and hence you'd want to drop back to using APITransactionTestCase.