Debian Codegraph @

tests/docker.py

raw symbols SCIP
1 import subprocess
2 import sys
3 import time
4 from os import path
5 import shutil
6
7 # base dir of sqlx workspace
8 dir_workspace = path.dirname(path.dirname(path.realpath(__file__)))
9
10 # dir of tests
11 dir_tests = path.join(dir_workspace, "tests")
12
13
14 # start database server and return a URL to use to connect
15 def start_database(driver, database, cwd):
16 if driver == "sqlite":
17 database = path.join(cwd, database)
18 (base_path, ext) = path.splitext(database)
19 new_database = f"{base_path}.test{ext}"
20 shutil.copy(database, new_database)
21 # short-circuit for sqlite
22 return f"sqlite://{path.join(cwd, new_database)}"
23
24 res = subprocess.run(
25 ["docker-compose", "up", "-d", driver],
26 stdout=subprocess.PIPE,
27 stderr=subprocess.PIPE,
28 cwd=dir_tests,
29 )
30
31 if res.returncode != 0:
32 print(res.stderr, file=sys.stderr)
33
34 if b"done" in res.stderr:
35 time.sleep(30)
36
37 # determine appropriate port for driver
38 if driver.startswith("mysql") or driver.startswith("mariadb"):
39 port = 3306
40
41 elif driver.startswith("postgres"):
42 port = 5432
43
44 else:
45 raise NotImplementedError
46
47 # find port
48 res = subprocess.run(
49 ["docker", "inspect", f"-f='{{{{(index (index .NetworkSettings.Ports \"{port}/tcp\") 0).HostPort}}}}'",
50 f"sqlx_{driver}_1"],
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE,
53 cwd=dir_tests,
54 )
55
56 if res.returncode != 0:
57 print(res.stderr, file=sys.stderr)
58
59 port = int(res.stdout[1:-2].decode())
60
61 # need additional permissions to connect to MySQL when using SSL
62 res = subprocess.run(
63 ["docker", "exec", f"sqlx_{driver}_1", "mysql", "-u", "root", "-e", "GRANT ALL PRIVILEGES ON *.* TO 'root' WITH GRANT OPTION;"],
64 stdout=subprocess.PIPE,
65 stderr=subprocess.PIPE,
66 cwd=dir_tests,
67 )
68
69 if res.returncode != 0:
70 print(res.stderr, file=sys.stderr)
71
72 # do not set password in URL if authenticating using SSL key file
73 if driver.endswith("client_ssl"):
74 password = ""
75 else:
76 password = ":password"
77
78 # construct appropriate database URL
79 if driver.startswith("mysql") or driver.startswith("mariadb"):
80 return f"mysql://root{password}@localhost:{port}/{database}"
81
82 elif driver.startswith("postgres"):
83 return f"postgres://postgres{password}@localhost:{port}/{database}"
84
85 else:
86 raise NotImplementedError