|
| 1 | +from django.db import connection |
1 | 2 | from django.test import TestCase
|
2 | 3 |
|
3 | 4 | from clickhouse_backend.driver import connect
|
4 | 5 |
|
| 6 | +from .. import models |
| 7 | + |
5 | 8 |
|
6 | 9 | class Tests(TestCase):
|
7 | 10 | def test_pool_size(self):
|
8 | 11 | conn = connect(host="localhost", connections_min=2, connections_max=4)
|
9 | 12 | assert conn.pool.connections_min == 2
|
10 | 13 | assert conn.pool.connections_max == 4
|
11 | 14 | assert len(conn.pool._pool) == 2
|
| 15 | + |
| 16 | + |
| 17 | +class IterationTests(TestCase): |
| 18 | + """ |
| 19 | + Testing connection behaviour when iterating over queryset is interrupted. |
| 20 | + """ |
| 21 | + |
| 22 | + @classmethod |
| 23 | + def setUpTestData(cls): |
| 24 | + cls.a1, cls.a2, cls.a3 = models.Author.objects.bulk_create( |
| 25 | + [ |
| 26 | + models.Author(name="a1"), |
| 27 | + models.Author(name="a2"), |
| 28 | + models.Author(name="a3"), |
| 29 | + ] |
| 30 | + ) |
| 31 | + |
| 32 | + def test_connection_not_reused_when_iteration_interrupted(self): |
| 33 | + """ |
| 34 | + This test demonstrates that if a queryset is iterated over and the |
| 35 | + iteration is interrupted (e.g. via a break statement), the connection |
| 36 | + used for that iteration is disconnected and not returned to the pool. |
| 37 | + """ |
| 38 | + pool = connection.connection.pool |
| 39 | + |
| 40 | + connection_count_before = len(pool._pool) |
| 41 | + assert connection_count_before == 1 |
| 42 | + |
| 43 | + authors = models.Author.objects.all() |
| 44 | + for author in authors.iterator(1): |
| 45 | + author = author.name |
| 46 | + break |
| 47 | + |
| 48 | + connection_count_after_iterator = len(pool._pool) |
| 49 | + # Connection was closed and not returned to pool |
| 50 | + assert connection_count_after_iterator == 0 |
| 51 | + |
| 52 | + author = authors.get(id=self.a1.id) |
0 commit comments