forked from cycle-five/action-setup-postgres
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_action.py
231 lines (160 loc) · 7.68 KB
/
test_action.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import locale
import os
import subprocess
import typing as t
import psycopg
import furl
import pytest
ConnectionFactory = t.Callable[[str], psycopg.Connection]
@pytest.fixture(scope="function")
def connection_uri() -> str:
"""Read and return connection URI from environment."""
connection_uri = os.getenv("CONNECTION_URI")
if connection_uri is None:
pytest.fail("CONNECTION_URI: environment variable is not set")
return connection_uri
@pytest.fixture(scope="function")
def service_name() -> str:
"""Read and return connection URI from environment."""
service_name = os.getenv("SERVICE_NAME")
if service_name is None:
pytest.fail("SERVICE_NAME: environment variable is not set")
return service_name
@pytest.fixture(scope="function")
def connection_factory() -> ConnectionFactory:
"""Return 'psycopg.Connection' factory."""
def factory(connection_uri: str) -> psycopg.Connection:
return psycopg.connect(connection_uri)
return factory
@pytest.fixture(scope="function", params=["uri", "kv-string"])
def connection(
request: pytest.FixtureRequest,
connection_factory: ConnectionFactory,
connection_uri: str,
service_name: str,
) -> psycopg.Connection:
"""Return 'psycopg.Connection' for connection URI set in environment."""
if request.param == "uri":
return connection_factory(connection_uri)
elif request.param == "kv-string":
return connection_factory(f"service={service_name}")
raise RuntimeError("f{request.param}: unknown value")
def test_connection_uri(connection_uri):
"""Test that CONNECTION_URI matches EXPECTED_CONNECTION_URI."""
assert connection_uri == os.getenv("EXPECTED_CONNECTION_URI")
def test_service_name(service_name):
"""Test that SERVICE_NAME matches EXPECTED_SERVICE_NAME."""
assert service_name == os.getenv("EXPECTED_SERVICE_NAME")
def test_server_encoding(connection: psycopg.Connection):
"""Test that PostgreSQL's encoding is 'UTF-8'."""
assert connection.execute("SHOW SERVER_ENCODING").fetchone()[0] == "UTF8"
def test_locale(connection: psycopg.Connection):
"""Test that PostgreSQL's locale is 'en_US.UTF-8'."""
lc_collate = connection.execute("SHOW LC_COLLATE").fetchone()[0]
lc_ctype = connection.execute("SHOW LC_CTYPE").fetchone()[0]
assert locale.normalize(lc_collate) == "en_US.UTF-8"
assert locale.normalize(lc_ctype) == "en_US.UTF-8"
def test_server_version(connection: psycopg.Connection):
"""Test that PostgreSQL's version is expected."""
server_version = connection.execute("SHOW SERVER_VERSION").fetchone()[0]
assert server_version.split(".")[0] == os.getenv("EXPECTED_SERVER_VERSION")
def test_user_permissions(connection: psycopg.Connection):
"""Test that a user has super/createdb permissions."""
with connection:
record = connection \
.execute("SELECT usecreatedb, usesuper FROM pg_user WHERE usename = CURRENT_USER") \
.fetchone()
assert record
usecreatedb, usesuper = record
assert usecreatedb
assert usesuper
def test_user_create_insert_select(connection: psycopg.Connection):
"""Test that a user has CRUD permissions in a database."""
table_name = "test_setup_postgres"
with connection, connection.transaction(force_rollback=True):
records = connection \
.execute(f"CREATE TABLE {table_name}(eggs INTEGER, rice VARCHAR)") \
.execute(f"INSERT INTO {table_name}(eggs, rice) VALUES (1, '42')") \
.execute(f"SELECT * FROM {table_name}") \
.fetchall()
assert records == [(1, "42")]
def test_user_create_insert_non_ascii(connection: psycopg.Connection):
"""Test that non-ASCII characters can be stored and fetched."""
table_name = "test_setup_postgres"
with connection, connection.transaction(force_rollback=True):
records = connection \
.execute(f"CREATE TABLE {table_name}(eggs INTEGER, rice VARCHAR)") \
.execute(f"INSERT INTO {table_name}(eggs, rice) VALUES (1, 'Україна')") \
.execute(f"INSERT INTO {table_name}(eggs, rice) VALUES (2, 'ウクライナ')") \
.execute(f"SELECT * FROM {table_name}") \
.fetchall()
assert records == [(1, "Україна"), (2, "ウクライナ")]
def test_user_create_drop_database(connection: psycopg.Connection):
"""Test that a user has permissions to create databases."""
# CREATE/DROP DATABASE statements don't work within transactions, and with
# autocommit disabled transactions are created by psycopg automatically.
connection.autocommit = True
database = "databas3"
connection.execute(f"CREATE DATABASE {database}")
connection.execute(f"DROP DATABASE {database}")
def test_user_create_drop_user(
connection: psycopg.Connection,
connection_factory: ConnectionFactory,
connection_uri: str
):
"""Test that a user has permissions to create users."""
# CREATE/DROP USER statements don't work within transactions, and with
# autocommit disabled transactions are created by psycopg automatically.
connection.autocommit = True
username = "us3rname"
password = "passw0rd"
database = "databas3"
connection.execute(f"CREATE USER {username} WITH PASSWORD '{password}'")
connection.execute(f"CREATE DATABASE {database} WITH OWNER '{username}'")
try:
# Smoke test that created user can successfully log-in and execute
# queries for its own database.
connection_uri = furl.furl(
connection_uri, username=username, password=password, path=database).url
test_user_create_insert_select(connection_factory(connection_uri))
finally:
connection.execute(f"DROP DATABASE {database}")
connection.execute(f"DROP USER {username}")
def test_client_applications(
connection_factory: ConnectionFactory,
service_name: str,
connection_uri: str,
monkeypatch: pytest.MonkeyPatch,
):
"""Test that PostgreSQL client applications can be used."""
# Request connection parameters from the connection service file prepared
# by our action.
monkeypatch.setenv("PGSERVICE", service_name)
username = "us3rname"
password = "passw0rd"
database = "databas3"
subprocess.check_call(["createuser", username])
subprocess.check_call(["createdb", "--owner", username, database])
subprocess.check_call(["psql", "-c", f"ALTER USER {username} WITH PASSWORD '{password}'"])
try:
# Smoke test that created user can successfully log-in and execute
# queries for its own database.
connection_uri = furl.furl(
connection_uri, username=username, password=password, path=database).url
test_user_create_insert_select(connection_factory(connection_uri))
finally:
subprocess.check_call(["dropdb", database])
subprocess.check_call(["dropuser", username])
def test_auth_wrong_username(connection_factory: ConnectionFactory, connection_uri: str):
"""Test that wrong username is rejected!"""
connection_furl = furl.furl(connection_uri, username="wrong")
with pytest.raises(psycopg.OperationalError) as excinfo:
connection_factory(connection_furl.url)
assert 'password authentication failed for user "wrong"' in str(excinfo.value)
def test_auth_wrong_password(connection_factory: ConnectionFactory, connection_uri: str):
"""Test that wrong password is rejected!"""
connection_furl = furl.furl(connection_uri, password="wrong")
username = connection_furl.username
with pytest.raises(psycopg.OperationalError) as excinfo:
connection_factory(connection_furl.url)
assert f'password authentication failed for user "{username}"' in str(excinfo.value)