|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
| 3 | +import os |
| 4 | +import subprocess |
| 5 | +import time |
3 | 6 | import warnings |
4 | 7 |
|
5 | | -import django |
6 | | -from django.db import connection |
7 | | -from pytest_django.plugin import blocking_manager_key |
| 8 | +import MySQLdb |
| 9 | +import pytest |
| 10 | +from django.conf import settings |
8 | 11 |
|
9 | 12 |
|
10 | | -def pytest_report_header(config): |
11 | | - dot_version = ".".join(str(x) for x in django.VERSION) |
12 | | - header = "Django version: " + dot_version |
| 13 | +@pytest.fixture(scope="session", autouse=True) |
| 14 | +def mysql_server(): |
| 15 | + image = os.environ.get("DB_IMAGE", "mariadb:11.4") |
| 16 | + name = f"django-mysql-test-{os.getpid()}" |
13 | 17 |
|
14 | | - pytest_django_db_blocker = config.stash[blocking_manager_key] |
15 | | - with pytest_django_db_blocker.unblock(), connection._nodb_cursor() as cursor: |
16 | | - cursor.execute("SELECT VERSION()") |
17 | | - version = cursor.fetchone()[0] |
18 | | - header += f"\nMySQL version: {version}" |
| 18 | + subprocess.run( |
| 19 | + [ |
| 20 | + "docker", |
| 21 | + "run", |
| 22 | + "--detach", |
| 23 | + "--name", |
| 24 | + name, |
| 25 | + "-e", |
| 26 | + "MYSQL_ROOT_PASSWORD=hunter2", |
| 27 | + "--publish", |
| 28 | + "127.0.0.1::3306", |
| 29 | + image, |
| 30 | + ], |
| 31 | + check=True, |
| 32 | + ) |
19 | 33 |
|
20 | | - return header |
| 34 | + try: |
| 35 | + port = ( |
| 36 | + subprocess.check_output( |
| 37 | + [ |
| 38 | + "docker", |
| 39 | + "inspect", |
| 40 | + name, |
| 41 | + "--format", |
| 42 | + '{{(index (index .NetworkSettings.Ports "3306/tcp") 0).HostPort}}', |
| 43 | + ] |
| 44 | + ) |
| 45 | + .decode() |
| 46 | + .strip() |
| 47 | + ) |
| 48 | + |
| 49 | + for db in settings.DATABASES.values(): |
| 50 | + if db["ENGINE"] != "django.db.backends.sqlite3": |
| 51 | + db["HOST"] = "127.0.0.1" |
| 52 | + db["PORT"] = port |
| 53 | + db["USER"] = "root" |
| 54 | + db["PASSWORD"] = "hunter2" |
| 55 | + |
| 56 | + deadline = time.monotonic() + 60 |
| 57 | + while True: |
| 58 | + try: |
| 59 | + conn = MySQLdb.connect( |
| 60 | + host="127.0.0.1", |
| 61 | + port=int(port), |
| 62 | + user="root", |
| 63 | + password="hunter2", |
| 64 | + ) |
| 65 | + conn.close() |
| 66 | + break |
| 67 | + except MySQLdb.OperationalError: |
| 68 | + if time.monotonic() > deadline: |
| 69 | + raise RuntimeError("MySQL did not become ready in time") |
| 70 | + time.sleep(0.5) |
| 71 | + |
| 72 | + yield |
| 73 | + finally: |
| 74 | + subprocess.run(["docker", "rm", "--force", name], check=True) |
21 | 75 |
|
22 | 76 |
|
23 | 77 | # MySQL 5.7 warns about some sql mode changes |
|
0 commit comments