/
conftest.py
1888 lines (1560 loc) · 71.5 KB
/
conftest.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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Copyright 2016 Inmanta
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Contact: code@inmanta.com
"""
import warnings
from tornado.httpclient import AsyncHTTPClient
import toml
from inmanta.logging import InmantaLoggerConfig
from inmanta.protocol import auth
"""
About the use of @parametrize_any and @slowtest:
For parametrized tests:
- if the test is fast and tests different things for each parameter, use @parametrize
- if the parameters only slightly increase the coverage of the test (some different exception path,...), use @parametrize_any.
- if a test is slow, use @parametrize_any
The @slowtest annotation is usually added on test periodically, when the test suite becomes too slow.
We analyze performance and place the @slowtest in the best places.
It is often harder to correctly judge what is slow up front, so we do it in bulk when we have all the (historical) data.
This also allows test to run a few hundred times before being marked as slow.
"""
"""
About venvs in tests (see linked objects' docstrings for more details):
During normal operation the module loader and the compiler work with the following environments:
- inmanta.env.process_env: inmanta.env.ActiveEnv -> presents an interface to interact with the outer (developer's) venv. Used by
inmanta.module.Project to install v2 modules in.
- inmanta.module.Project.virtualenv: inmanta.env.VirtualEnv -> compiler venv. Used by the compiler to install v1 module
requirements in. Inherits from the outer venv.
When running the tests we don't want to make changes to the outer environment. So for tests that install Python packages we need
to make sure those are installed in a test environment. This means patching the inmanta.env.process_env to be an interface
to a test environment instead of the outer environment.
The following fixtures manage test environments:
- snippetcompiler_clean: activates the Project's compiler venv and patches inmanta.env.process_env to use this same venv
as if it were the outer venv. The activation and patch is applied when compiling the first snippet.
- snippetcompiler: same as snippetcompiler_clean but the compiler venv is shared among all tests using the
fixture.
- tmpvenv: provides a decoupled test environment (does not inherit from the outer environment) but does not activate it and
does not patch inmanta.env.process_env.
- tmpvenv_active: provides a decoupled test environment, activates it and patches inmanta.env.process_env to point to this
environment.
The deactive_venv autouse fixture cleans up all venv activation and resets inmanta.env.process_env to point to the outer
environment.
"""
import asyncio
import concurrent
import csv
import datetime
import json
import logging
import os
import queue
import random
import re
import shutil
import site
import socket
import string
import subprocess
import sys
import tempfile
import time
import traceback
import uuid
import venv
from collections import abc
from collections.abc import AsyncIterator, Awaitable, Iterator
from configparser import ConfigParser
from typing import Callable, Dict, Optional, Union
import asyncpg
import pkg_resources
import psutil
import py
import pyformance
import pytest
from asyncpg.exceptions import DuplicateDatabaseError
from click import testing
from pkg_resources import Requirement
from pyformance.registry import MetricsRegistry
from tornado import netutil
import build.env
import inmanta
import inmanta.agent
import inmanta.app
import inmanta.compiler as compiler
import inmanta.compiler.config
import inmanta.main
import inmanta.user_setup
from inmanta import config, const, data, env, loader, protocol, resources
from inmanta.agent import config as agent_cfg
from inmanta.agent import handler
from inmanta.agent.agent import Agent
from inmanta.ast import CompilerException
from inmanta.data.schema import SCHEMA_VERSION_TABLE
from inmanta.db import util as db_util
from inmanta.env import CommandRunner, LocalPackagePath, VirtualEnv, mock_process_env
from inmanta.export import ResourceDict, cfg_env, unknown_parameters
from inmanta.module import InmantaModuleRequirement, InstallMode, Project, RelationPrecedenceRule
from inmanta.moduletool import DefaultIsolatedEnvCached, ModuleTool, V2ModuleBuilder
from inmanta.parser.plyInmantaParser import cache_manager
from inmanta.protocol import VersionMatch
from inmanta.server import SLICE_AGENT_MANAGER, SLICE_COMPILER
from inmanta.server.bootloader import InmantaBootloader
from inmanta.server.protocol import Server, SliceStartupException
from inmanta.server.services import orchestrationservice
from inmanta.server.services.compilerservice import CompilerService, CompileRun
from inmanta.types import JsonType
from inmanta.warnings import WarningsManager
from libpip2pi.commands import dir2pi
from packaging.version import Version
from pytest_postgresql import factories
# Import test modules differently when conftest is put into the inmanta_tests packages
PYTEST_PLUGIN_MODE: bool = __file__ and os.path.dirname(__file__).split("/")[-1] == "inmanta_tests"
if PYTEST_PLUGIN_MODE:
from inmanta_tests import utils # noqa: F401
else:
import utils
# These elements were moved to inmanta.db.util to allow them to be used from other extensions.
# This import statement is present to ensure backwards compatibility.
from inmanta.db.util import MODE_READ_COMMAND, MODE_READ_INPUT, AsyncSingleton, PGRestore # noqa: F401
from inmanta.db.util import clear_database as do_clean_hard # noqa: F401
from inmanta.db.util import postgres_get_custom_types as postgress_get_custom_types # noqa: F401
logger = logging.getLogger(__name__)
TABLES_TO_KEEP = [x.table_name() for x in data._classes] + ["resourceaction_resource"] # Join table
# Save the cwd as early as possible to prevent that it gets overridden by another fixture
# before it's saved.
initial_cwd = os.getcwd()
pg_logfile = os.path.join(initial_cwd, "pg.log")
def _pytest_configure_plugin_mode(config: "pytest.Config") -> None:
# register custom markers
config.addinivalue_line(
"markers",
"slowtest",
)
config.addinivalue_line(
"markers",
"parametrize_any: only execute one of the parameterized cases when in fast mode (see documentation in conftest.py)",
)
config.addinivalue_line(
"markers",
"db_restore_dump(dump): mark the db dump to restore. To be used in conjunction with the `migrate_db_from` fixture.",
)
def pytest_configure(config: "pytest.Config") -> None:
if PYTEST_PLUGIN_MODE:
_pytest_configure_plugin_mode(config)
def pytest_addoption(parser):
parser.addoption(
"--fast",
action="store_true",
help="Don't run all test, but a representative set",
)
@pytest.hookimpl(tryfirst=True)
def pytest_generate_tests(metafunc: "pytest.Metafunc") -> None:
"""
For each test marked as parametrize_any run it either as
1. if not in fast mode: as if annotated with @parametrize
2. if in fast mode: with only one parameter combination, chosen randomly
"""
is_fast = metafunc.config.getoption("fast")
for marker in metafunc.definition.iter_markers(name="parametrize_any"):
variations = len(marker.args[1])
if not is_fast or variations < 2:
metafunc.definition.add_marker(pytest.mark.parametrize(*marker.args))
else:
# select one random item
args = list(marker.args)
selected = args[1][random.randrange(0, variations)]
args[1] = [selected]
metafunc.definition.add_marker(pytest.mark.parametrize(*args))
def pytest_runtest_setup(item: "pytest.Item"):
"""
When in fast mode, skip test marked as slow and db_migration tests that are older than 30 days.
"""
is_fast = item.config.getoption("fast")
if not is_fast:
return
if any(True for mark in item.iter_markers(name="slowtest")):
pytest.skip("Skipping slow tests")
file_name: str = item.location[0]
if file_name.startswith("tests/db/migration_tests"):
match: Optional[re.Match] = re.fullmatch("tests/db/migration_tests/test_v[0-9]{9}_to_v([0-9]{8})[0-9].py", file_name)
if not match:
pytest.fail(
"The name of the test file might be incorrect: Should be test_v<old_version>_to_v<new_version>.py or the test "
"should have the @slowtest annotation"
)
timestamp: str = match.group(1)
test_creation_date: datetime.datetime = datetime.datetime(int(timestamp[0:4]), int(timestamp[4:6]), int(timestamp[6:8]))
elapsed_days: int = (datetime.datetime.today() - test_creation_date).days
if elapsed_days > 30:
pytest.skip("Skipping old migration test")
# adds a custom log location for postgres
postgresql_proc_with_log = factories.postgresql_proc(startparams=f"--log='{pg_logfile}'")
@pytest.fixture(scope="session")
def postgres_db(request: pytest.FixtureRequest):
"""This fixture loads the pytest-postgresql fixture. When --postgresql-host is set, it will use the noproc
fixture to use an external database. Without this option, an "embedded" postgres is started.
"""
option_name = "postgresql_host"
conf = request.config.getoption(option_name)
if conf:
fixture = "postgresql_noproc"
else:
fixture = "postgresql_proc_with_log"
logger.info("Using database fixture %s", fixture)
pg = request.getfixturevalue(fixture)
yield pg
if os.path.exists(pg_logfile):
has_deadlock = False
with open(pg_logfile) as fh:
for line in fh:
if "deadlock" in line:
has_deadlock = True
break
sublogger = logging.getLogger("pytest.postgresql.deadlock")
for line in fh:
sublogger.warning("%s", line)
os.remove(pg_logfile)
assert not has_deadlock
@pytest.fixture
async def run_without_keeping_psql_logs(postgres_db):
if os.path.exists(pg_logfile):
# Store the original content of the logfile
with open(pg_logfile) as file:
original_content = file.read()
yield
if os.path.exists(pg_logfile):
# Restore the original content of the logfile
with open(pg_logfile, "w") as file:
file.write(original_content)
@pytest.fixture
async def postgres_db_debug(postgres_db, database_name) -> abc.AsyncIterator[None]:
"""
Fixture meant for debugging through manual interaction with the database. Run pytest with `-s/--capture=no`.
"""
yield
print(
"Connection to DB will be kept alive for one hour. Connect with"
f" `psql --host localhost --port {postgres_db.port} {database_name} {postgres_db.user}`"
)
await asyncio.sleep(3600)
@pytest.fixture
def ensure_running_postgres_db_post(postgres_db):
yield
if not postgres_db.running():
postgres_db.start()
@pytest.fixture(scope="function")
async def create_db(postgres_db, database_name_internal):
"""
see :py:database_name_internal:
"""
connection = await asyncpg.connect(
host=postgres_db.host, port=postgres_db.port, user=postgres_db.user, password=postgres_db.password
)
try:
await connection.execute(f"CREATE DATABASE {database_name_internal}")
except DuplicateDatabaseError:
# Because it is async, this fixture can not be made session scoped.
# Only the first time it is called, it will actually create a database
# All other times will drop through here
pass
finally:
await connection.close()
return database_name_internal
@pytest.fixture(scope="session")
def database_name_internal():
"""
Internal use only, use database_name instead.
The database_name fixture is expected to yield the database name to an existing database, and should be session scoped.
To create the database we need asyncpg. However, async fixtures all depend on the event loop.
The event loop is function scoped.
To resolve this, there is a session scoped fixture called database_name_internal that provides a fixed name. create_db
ensures that the database has been created.
"""
ten_random_digits = "".join(random.choice(string.digits) for _ in range(10))
return "inmanta" + ten_random_digits
@pytest.fixture(scope="function")
def database_name(create_db):
return create_db
@pytest.fixture(scope="function")
async def postgresql_client(postgres_db, database_name):
client = await asyncpg.connect(
host=postgres_db.host,
port=postgres_db.port,
user=postgres_db.user,
password=postgres_db.password,
database=database_name,
)
yield client
await client.close()
@pytest.fixture(scope="function")
async def postgresql_pool(postgres_db, database_name):
client = await asyncpg.create_pool(
host=postgres_db.host,
port=postgres_db.port,
user=postgres_db.user,
password=postgres_db.password,
database=database_name,
)
yield client
await client.close()
@pytest.fixture(scope="function")
async def init_dataclasses_and_load_schema(postgres_db, database_name, clean_reset):
await data.connect(
host=postgres_db.host,
port=postgres_db.port,
username=postgres_db.user,
password=postgres_db.password,
database=database_name,
)
yield
await data.disconnect()
@pytest.fixture(scope="function")
async def hard_clean_db(postgresql_client):
await db_util.clear_database(postgresql_client)
yield
@pytest.fixture(scope="function")
async def hard_clean_db_post(postgresql_client):
yield
await db_util.clear_database(postgresql_client)
@pytest.fixture(scope="function")
async def clean_db(postgresql_pool, create_db, postgres_db):
"""
1) Truncated tables: All tables which are part of the inmanta schema, except for the schemaversion table. The version
number stored in the schemaversion table is read by the Inmanta server during startup.
2) Dropped tables: All tables which are not part of the inmanta schema. Some tests create additional tables, which are
not part of the Inmanta schema. These should be cleaned-up before running a new test.
"""
yield
# By using the connection pool, we can make sure that the connection we use is alive
async with postgresql_pool.acquire() as postgresql_client:
tables_in_db = await postgresql_client.fetch(
"SELECT table_name FROM information_schema.tables WHERE table_schema='public'"
)
tables_in_db = [x["table_name"] for x in tables_in_db]
tables_to_preserve = TABLES_TO_KEEP
tables_to_preserve.append(SCHEMA_VERSION_TABLE)
tables_to_truncate = [x for x in tables_in_db if x in tables_to_preserve and x != SCHEMA_VERSION_TABLE]
tables_to_drop = [x for x in tables_in_db if x not in tables_to_preserve]
if tables_to_drop:
drop_query = "DROP TABLE %s CASCADE" % ", ".join(tables_to_drop)
await postgresql_client.execute(drop_query)
if tables_to_truncate:
truncate_query = "TRUNCATE %s CASCADE" % ", ".join(tables_to_truncate)
await postgresql_client.execute(truncate_query)
@pytest.fixture(scope="function")
def get_columns_in_db_table(postgresql_client):
async def _get_columns_in_db_table(table_name: str) -> list[str]:
result = await postgresql_client.fetch(
"SELECT column_name "
"FROM information_schema.columns "
"WHERE table_schema='public' AND table_name='" + table_name + "'"
)
return [r["column_name"] for r in result]
return _get_columns_in_db_table
@pytest.fixture(scope="function")
def get_primary_key_columns_in_db_table(postgresql_client):
async def _get_primary_key_columns_in_db_table(table_name: str) -> list[str]:
# Query taken from here: https://wiki.postgresql.org/wiki/Retrieve_primary_key_columns
result = await postgresql_client.fetch(
"SELECT a.attname FROM pg_index i "
"JOIN pg_attribute a ON a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey) "
"WHERE i.indrelid = '" + table_name + "'::regclass "
"AND i.indisprimary;"
)
return [r["attname"] for r in result]
return _get_primary_key_columns_in_db_table
@pytest.fixture(scope="function")
def get_tables_in_db(postgresql_client):
async def _get_tables_in_db() -> list[str]:
result = await postgresql_client.fetch("SELECT table_name FROM information_schema.tables WHERE table_schema='public'")
return [r["table_name"] for r in result]
return _get_tables_in_db
@pytest.fixture(scope="function")
def get_custom_postgresql_types(postgresql_client) -> Callable[[], Awaitable[list[str]]]:
"""
Fixture that returns an async callable that returns all the custom types defined
in the PostgreSQL database.
"""
async def f() -> list[str]:
return await db_util.postgres_get_custom_types(postgresql_client)
return f
@pytest.fixture(scope="function")
def get_type_of_column(postgresql_client) -> Callable[[], Awaitable[Optional[str]]]:
"""
Fixture that returns the type of a column in a table
"""
async def _get_type_of_column(table_name: str, column_name: str) -> Optional[str]:
data_type = await postgresql_client.fetchval(
"""
SELECT data_type
FROM information_schema.columns
WHERE table_schema = 'public'
AND table_name = $1
AND column_name = $2;
""",
table_name,
column_name,
)
return data_type
return _get_type_of_column
@pytest.fixture(scope="function")
def deactive_venv():
old_os_path = os.environ.get("PATH", "")
old_prefix = sys.prefix
old_path = list(sys.path)
old_meta_path = sys.meta_path.copy()
old_path_hooks = sys.path_hooks.copy()
old_pythonpath = os.environ.get("PYTHONPATH", None)
old_os_venv: Optional[str] = os.environ.get("VIRTUAL_ENV", None)
old_process_env: str = env.process_env.python_path
old_working_set = pkg_resources.working_set
old_available_extensions = (
dict(InmantaBootloader.AVAILABLE_EXTENSIONS) if InmantaBootloader.AVAILABLE_EXTENSIONS is not None else None
)
yield
os.environ["PATH"] = old_os_path
sys.prefix = old_prefix
sys.path = old_path
# reset sys.meta_path because it might contain finders for editable installs, make sure to keep the same object
sys.meta_path.clear()
sys.meta_path.extend(old_meta_path)
sys.path_hooks.clear()
sys.path_hooks.extend(old_path_hooks)
# Clear cache for sys.path_hooks
sys.path_importer_cache.clear()
pkg_resources.working_set = old_working_set
# Restore PYTHONPATH
if old_pythonpath is not None:
os.environ["PYTHONPATH"] = old_pythonpath
elif "PYTHONPATH" in os.environ:
del os.environ["PYTHONPATH"]
# Restore VIRTUAL_ENV
if old_os_venv is not None:
os.environ["VIRTUAL_ENV"] = old_os_venv
elif "VIRTUAL_ENV" in os.environ:
del os.environ["VIRTUAL_ENV"]
env.mock_process_env(python_path=old_process_env)
loader.PluginModuleFinder.reset()
InmantaBootloader.AVAILABLE_EXTENSIONS = old_available_extensions
def reset_metrics():
pyformance.set_global_registry(MetricsRegistry())
@pytest.fixture(scope="function", autouse=True)
async def clean_reset(create_db, clean_db, deactive_venv):
reset_all_objects()
config.Config._reset()
methods = inmanta.protocol.common.MethodProperties.methods.copy()
loader.unload_inmanta_plugins()
default_settings = dict(data.Environment._settings)
yield
inmanta.protocol.common.MethodProperties.methods = methods
config.Config._reset()
reset_all_objects()
loader.unload_inmanta_plugins()
cache_manager.detach_from_project()
data.Environment._settings = default_settings
@pytest.fixture(scope="session", autouse=True)
def clean_reset_session():
"""
Execute cleanup tasks that should only run at the end of the test suite.
"""
yield
DefaultIsolatedEnvCached.get_instance().destroy()
def reset_all_objects():
resources.resource.reset()
asyncio.set_child_watcher(None)
reset_metrics()
# No dynamic loading of commands at the moment, so no need to reset/reload
# command.Commander.reset()
handler.Commander.reset()
Project._project = None
unknown_parameters.clear()
InmantaBootloader.AVAILABLE_EXTENSIONS = None
V2ModuleBuilder.DISABLE_DEFAULT_ISOLATED_ENV_CACHED = False
compiler.Finalizers.reset_finalizers()
auth.AuthJWTConfig.reset()
InmantaLoggerConfig.clean_instance()
AsyncHTTPClient.configure(None)
@pytest.fixture()
def disable_isolated_env_builder_cache() -> None:
V2ModuleBuilder.DISABLE_DEFAULT_ISOLATED_ENV_CACHED = True
@pytest.fixture(scope="function", autouse=True)
def restore_cwd():
"""
Restore the current working directory after search test.
"""
yield
os.chdir(initial_cwd)
@pytest.fixture(scope="function")
def no_agent_backoff(inmanta_config: ConfigParser) -> None:
old_backoff = agent_cfg.agent_get_resource_backoff.get()
inmanta_config.set(section="config", option="agent-get-resource-backoff", value="0")
yield
inmanta_config.set(section="config", option="agent-get-resource-backoff", value=str(old_backoff))
@pytest.fixture()
def free_socket():
bound_sockets = []
def _free_socket():
sock = netutil.bind_sockets(0, "127.0.0.1", family=socket.AF_INET)[0]
bound_sockets.append(sock)
return sock
yield _free_socket
for s in bound_sockets:
s.close()
@pytest.fixture(scope="function", autouse=True)
def inmanta_config() -> Iterator[ConfigParser]:
config.Config.load_config()
config.Config.set("auth_jwt_default", "algorithm", "HS256")
config.Config.set("auth_jwt_default", "sign", "true")
config.Config.set("auth_jwt_default", "client_types", "agent,compiler,api")
config.Config.set("auth_jwt_default", "key", "rID3kG4OwGpajIsxnGDhat4UFcMkyFZQc1y3oKQTPRs")
config.Config.set("auth_jwt_default", "expire", "0")
config.Config.set("auth_jwt_default", "issuer", "https://localhost:8888/")
config.Config.set("auth_jwt_default", "audience", "https://localhost:8888/")
yield config.Config.get_instance()
@pytest.fixture
def server_pre_start(server_config):
"""This fixture is called by the server. Override this fixture to influence server config"""
@pytest.fixture(scope="function")
async def agent_multi(server_multi, environment_multi):
agentmanager = server_multi.get_slice(SLICE_AGENT_MANAGER)
config.Config.set("config", "agent-deploy-interval", "0")
config.Config.set("config", "agent-repair-interval", "0")
a = Agent(hostname="node1", environment=environment_multi, agent_map={"agent1": "localhost"}, code_loader=False)
await a.add_end_point_name("agent1")
await a.start()
await utils.retry_limited(lambda: len(agentmanager.sessions) == 1, 10)
yield a
await a.stop()
@pytest.fixture(scope="function")
async def agent(server, environment):
agentmanager = server.get_slice(SLICE_AGENT_MANAGER)
config.Config.set("config", "agent-deploy-interval", "0")
config.Config.set("config", "agent-repair-interval", "0")
a = Agent(hostname="node1", environment=environment, agent_map={"agent1": "localhost"}, code_loader=False)
await a.add_end_point_name("agent1")
await a.start()
await utils.retry_limited(lambda: len(agentmanager.sessions) == 1, 10)
yield a
await a.stop()
@pytest.fixture(scope="function")
async def agent_factory(server):
agentmanager = server.get_slice(SLICE_AGENT_MANAGER)
config.Config.set("config", "agent-deploy-interval", "0")
config.Config.set("config", "agent-repair-interval", "0")
started_agents = []
async def create_agent(
environment: uuid.UUID,
hostname: Optional[str] = None,
agent_map: Optional[dict[str, str]] = None,
code_loader: bool = False,
agent_names: list[str] = [],
) -> Agent:
a = Agent(hostname=hostname, environment=environment, agent_map=agent_map, code_loader=code_loader)
for agent_name in agent_names:
await a.add_end_point_name(agent_name)
await a.start()
started_agents.append(a)
await utils.retry_limited(lambda: a.sessionid in agentmanager.sessions, 10)
return a
yield create_agent
await asyncio.gather(*[agent.stop() for agent in started_agents])
@pytest.fixture(scope="function")
async def autostarted_agent(server, client, environment):
"""Configure agent1 as an autostarted agent."""
result = await client.set_setting(environment, data.AUTOSTART_AGENT_MAP, {"internal": "", "agent1": ""})
assert result.code == 200
result = await client.set_setting(environment, data.AUTO_DEPLOY, True)
assert result.code == 200
result = await client.set_setting(environment, data.PUSH_ON_AUTO_DEPLOY, True)
assert result.code == 200
# disable deploy and repair intervals
result = await client.set_setting(environment, data.AUTOSTART_AGENT_DEPLOY_INTERVAL, 0)
assert result.code == 200
result = await client.set_setting(environment, data.AUTOSTART_AGENT_REPAIR_INTERVAL, 0)
assert result.code == 200
result = await client.set_setting(environment, data.AUTOSTART_ON_START, True)
assert result.code == 200
@pytest.fixture(scope="function")
def client_v2(server):
client = protocol.Client("client", version_match=VersionMatch.exact, exact_version=2)
yield client
@pytest.fixture(scope="session")
def log_file():
output_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "logs")
if not os.path.exists(output_dir):
os.mkdir(output_dir)
output_file = os.path.join(output_dir, "log.txt")
with open(output_file, "w", encoding="utf-8") as f:
yield f
@pytest.fixture(scope="function", autouse="DEBUG_TCP_PORTS" in os.environ)
def log_state_tcp_ports(request, log_file):
def _write_log_line(title):
connections = psutil.net_connections()
writer = csv.writer(log_file, dialect="unix")
def map_data_line(line):
out = [
title,
line.fd,
str(line.family),
str(line.type),
f"{line.laddr.ip}|{line.laddr.port}" if line.laddr else None,
f"{line.raddr.ip}|{line.raddr.port}" if line.raddr else None,
line.status,
None if "pid" not in line else line.pid,
]
return out
for con in connections:
writer.writerow(map_data_line(con))
_write_log_line(f"Before run test case {request.function.__name__}:")
yield
_write_log_line(f"After run test case {request.function.__name__}:")
@pytest.fixture(scope="function")
async def server_config(event_loop, inmanta_config, postgres_db, database_name, clean_reset, unused_tcp_port_factory):
reset_metrics()
with tempfile.TemporaryDirectory() as state_dir:
port = str(unused_tcp_port_factory())
config.Config.set("database", "name", database_name)
config.Config.set("database", "host", "localhost")
config.Config.set("database", "port", str(postgres_db.port))
config.Config.set("database", "username", postgres_db.user)
config.Config.set("database", "password", postgres_db.password)
config.Config.set("database", "connection_timeout", str(3))
config.Config.set("config", "state-dir", state_dir)
config.Config.set("config", "log-dir", os.path.join(state_dir, "logs"))
config.Config.set("agent_rest_transport", "port", port)
config.Config.set("compiler_rest_transport", "port", port)
config.Config.set("client_rest_transport", "port", port)
config.Config.set("cmdline_rest_transport", "port", port)
config.Config.set("server", "bind-port", port)
config.Config.set("server", "bind-address", "127.0.0.1")
config.Config.set("server", "agent-process-purge-interval", "0")
config.Config.set("config", "executable", os.path.abspath(inmanta.app.__file__))
config.Config.set("server", "agent-timeout", "2")
config.Config.set("agent", "agent-repair-interval", "0")
yield config
@pytest.fixture(scope="function")
async def server(server_pre_start) -> abc.AsyncIterator[Server]:
"""
:param event_loop: explicitly include event_loop to make sure event loop started before and closed after this fixture.
May not be required
"""
# fix for fact that pytest_tornado never set IOLoop._instance, the IOLoop of the main thread
# causes handler failure
ibl = InmantaBootloader()
try:
await ibl.start()
except SliceStartupException as e:
port = config.Config.get("server", "bind-port")
output = subprocess.check_output(["ss", "-antp"])
output = output.decode("utf-8")
logger.debug(f"Port: {port}")
logger.debug(f"Port usage: \n {output}")
raise e
yield ibl.restserver
try:
await ibl.stop(timeout=15)
except concurrent.futures.TimeoutError:
logger.exception("Timeout during stop of the server in teardown")
logger.info("Server clean up done")
@pytest.fixture(
scope="function",
params=[(True, True, False), (True, False, False), (False, True, False), (False, False, False), (True, True, True)],
ids=["SSL and Auth", "SSL", "Auth", "Normal", "SSL and Auth with not self signed certificate"],
)
async def server_multi(
server_pre_start, event_loop, inmanta_config, postgres_db, database_name, request, clean_reset, unused_tcp_port_factory
):
"""
:param event_loop: explicitly include event_loop to make sure event loop started before and closed after this fixture.
May not be required
"""
with tempfile.TemporaryDirectory() as state_dir:
ssl, auth, ca = request.param
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")
if auth:
config.Config.set("server", "auth", "true")
for x, ct in [
("server", None),
("agent_rest_transport", ["agent"]),
("compiler_rest_transport", ["compiler"]),
("client_rest_transport", ["api", "compiler"]),
("cmdline_rest_transport", ["api"]),
]:
if ssl and not ca:
config.Config.set(x, "ssl_cert_file", os.path.join(path, "server.crt"))
config.Config.set(x, "ssl_key_file", os.path.join(path, "server.open.key"))
config.Config.set(x, "ssl_ca_cert_file", os.path.join(path, "server.crt"))
config.Config.set(x, "ssl", "True")
if ssl and ca:
capath = os.path.join(path, "ca", "enduser-certs")
config.Config.set(x, "ssl_cert_file", os.path.join(capath, "server.crt"))
config.Config.set(x, "ssl_key_file", os.path.join(capath, "server.key.open"))
config.Config.set(x, "ssl_ca_cert_file", os.path.join(capath, "server.chain"))
config.Config.set(x, "ssl", "True")
if auth and ct is not None:
token = protocol.encode_token(ct)
config.Config.set(x, "token", token)
port = str(unused_tcp_port_factory())
config.Config.set("database", "name", database_name)
config.Config.set("database", "host", "localhost")
config.Config.set("database", "port", str(postgres_db.port))
config.Config.set("database", "username", postgres_db.user)
config.Config.set("database", "password", postgres_db.password)
config.Config.set("database", "connection_timeout", str(3))
config.Config.set("config", "state-dir", state_dir)
config.Config.set("config", "log-dir", os.path.join(state_dir, "logs"))
config.Config.set("agent_rest_transport", "port", port)
config.Config.set("compiler_rest_transport", "port", port)
config.Config.set("client_rest_transport", "port", port)
config.Config.set("cmdline_rest_transport", "port", port)
config.Config.set("server", "bind-port", port)
config.Config.set("server", "bind-address", "127.0.0.1")
config.Config.set("config", "executable", os.path.abspath(inmanta.app.__file__))
config.Config.set("server", "agent-timeout", "2")
config.Config.set("agent", "agent-repair-interval", "0")
ibl = InmantaBootloader()
try:
await ibl.start()
except SliceStartupException as e:
port = config.Config.get("server", "bind-port")
output = subprocess.check_output(["ss", "-antp"])
output = output.decode("utf-8")
logger.debug(f"Port: {port}")
logger.debug(f"Port usage: \n {output}")
raise e
yield ibl.restserver
try:
await ibl.stop(timeout=15)
except concurrent.futures.TimeoutError:
logger.exception("Timeout during stop of the server in teardown")
@pytest.fixture(scope="function")
def client(server):
client = protocol.Client("client")
yield client
@pytest.fixture(scope="function")
def client_multi(server_multi):
client = protocol.Client("client")
yield client
@pytest.fixture(scope="function")
def sync_client_multi(server_multi):
client = protocol.SyncClient("client")
yield client
@pytest.fixture(scope="function")
def clienthelper(client, environment):
return utils.ClientHelper(client, environment)
@pytest.fixture(scope="function", autouse=True)
def capture_warnings():
# Ensure that the test suite uses the same config for warnings as the default config used by the CLI tools.
logging.captureWarnings(True)
cmd_parser = inmanta.app.cmd_parser()
WarningsManager.apply_config({"default": cmd_parser.get_default("warnings")})
yield
warnings.resetwarnings()
logging.captureWarnings(False)
@pytest.fixture
async def project_default(server, client) -> AsyncIterator[str]:
"""
Fixture that creates a new inmanta project called env-test.
"""
result = await client.create_project("env-test")
assert result.code == 200
yield result.result["project"]["id"]
@pytest.fixture
async def project_multi(server_multi, client_multi) -> AsyncIterator[str]:
"""
Does the same as the project fixture, but this fixture should be used instead when the test case
uses the server_multi or client_multi fixture.
"""
result = await client_multi.create_project("env-test")
assert result.code == 200
yield result.result["project"]["id"]
@pytest.fixture
async def environment_creator() -> AsyncIterator[Callable[[protocol.Client, str, str, bool], Awaitable[str]]]:
"""
Fixture to create a new environment in a certain project.
"""
async def _create_environment(client, project_id: str, env_name: str, use_custom_env_settings: bool = True) -> str:
"""
:param client: The client that should be used to create the project and environment.
:param use_custom_env_settings: True iff the auto_deploy features is disabled and the
agent trigger method is set to push_full_deploy.
:return: The uuid of the newly created environment as a string.
"""
result = await client.create_environment(project_id=project_id, name=env_name)
env_id = result.result["environment"]["id"]
cfg_env.set(env_id)
if use_custom_env_settings:
env_obj = await data.Environment.get_by_id(uuid.UUID(env_id))
await env_obj.set(data.AUTO_DEPLOY, False)
await env_obj.set(data.PUSH_ON_AUTO_DEPLOY, False)
await env_obj.set(data.AGENT_TRIGGER_METHOD_ON_AUTO_DEPLOY, const.AgentTriggerMethod.push_full_deploy)
await env_obj.set(data.RECOMPILE_BACKOFF, 0)
return env_id
yield _create_environment
@pytest.fixture(scope="function")
async def environment(
server, client, project_default: str, environment_creator: Callable[[protocol.Client, str, str, bool], Awaitable[str]]
) -> AsyncIterator[str]:
"""
Create a project and environment, with auto_deploy turned off and push_full_deploy set to push_full_deploy.
This fixture returns the uuid of the environment.
"""
yield await environment_creator(client, project_id=project_default, env_name="dev", use_custom_env_settings=True)
@pytest.fixture(scope="function")
async def environment_default(
server, client, project_default: str, environment_creator: Callable[[protocol.Client, str, str, bool], Awaitable[str]]