-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconftest.py
1982 lines (1768 loc) · 69.3 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
import os
import time
import timeit
from datetime import datetime
from pathlib import Path
from typing import Iterable, List, Mapping, Optional
import codes
import models
import psycopg2
import pytest
import sqlalchemy
from alembic import command
from alembic.config import Config
from alembic.operations import ops
from alembic.script import ScriptDirectory
from base import PROJECT_SRID
from db_helper import DatabaseHelper
from db_manager import db_manager
from dotenv import load_dotenv
from geoalchemy2.shape import from_shape
from shapely.geometry import MultiLineString, MultiPoint, shape
from sqlalchemy.dialects.postgresql import Range
from sqlalchemy.orm import Session, sessionmaker
hame_count: int = 14 # adjust me when adding tables
codes_count: int = 16 # adjust me when adding tables
matview_count: int = 0 # adjust me when adding views
USE_DOCKER = (
"1" # Use "" if you don't want pytest-docker to start and destroy the containers
)
SCHEMA_FILES_PATH = Path(".")
@pytest.fixture(scope="session", autouse=True)
def set_env():
dotenv_file = Path(__file__).parent.parent.parent / ".env"
assert dotenv_file.exists()
load_dotenv(str(dotenv_file))
db_manager.SCHEMA_FILES_PATH = str(Path(__file__).parent.parent)
@pytest.fixture(scope="session")
def root_db_params():
return {
"dbname": os.environ.get("DB_MAINTENANCE_NAME", ""),
"user": os.environ.get("SU_USER", ""),
"host": os.environ.get("DB_INSTANCE_ADDRESS", ""),
"password": os.environ.get("SU_USER_PW", ""),
"port": os.environ.get("DB_INSTANCE_PORT", ""),
}
@pytest.fixture(scope="session")
def main_db_params():
return {
"dbname": os.environ.get("DB_MAIN_NAME", ""),
"user": os.environ.get("RW_USER", ""),
"host": os.environ.get("DB_INSTANCE_ADDRESS", ""),
"password": os.environ.get("RW_USER_PW", ""),
"port": os.environ.get("DB_INSTANCE_PORT", ""),
}
@pytest.fixture(scope="session")
def main_db_params_with_root_user():
return {
"dbname": os.environ.get("DB_MAIN_NAME", ""),
"user": os.environ.get("SU_USER", ""),
"host": os.environ.get("DB_INSTANCE_ADDRESS", ""),
"password": os.environ.get("SU_USER_PW", ""),
"port": os.environ.get("DB_INSTANCE_PORT", ""),
}
@pytest.fixture(scope="session")
def docker_compose_file(pytestconfig):
compose_file = Path(__file__).parent.parent.parent / "docker-compose.dev.yml"
assert compose_file.exists()
return str(compose_file)
if os.environ.get("MANAGE_DOCKER", USE_DOCKER):
@pytest.fixture(scope="session", autouse=True)
def wait_for_services(docker_services, main_db_params, root_db_params):
def is_responsive(params):
succeeds = False
try:
with psycopg2.connect(**root_db_params):
succeeds = True
except psycopg2.OperationalError:
pass
return succeeds
wait_until_responsive(
timeout=20, pause=0.5, check=lambda: is_responsive(root_db_params)
)
drop_hame_db(main_db_params, root_db_params)
else:
@pytest.fixture(scope="session", autouse=True)
def wait_for_services(main_db_params, root_db_params):
wait_until_responsive(
timeout=20, pause=0.5, check=lambda: is_responsive(root_db_params)
)
drop_hame_db(main_db_params, root_db_params)
@pytest.fixture(scope="session")
def alembic_cfg():
return Config(Path(SCHEMA_FILES_PATH, "alembic.ini"))
@pytest.fixture(scope="session")
def current_head_version_id(alembic_cfg):
script_dir = ScriptDirectory.from_config(alembic_cfg)
return script_dir.get_current_head()
@pytest.fixture(scope="module")
def hame_database_created(root_db_params, main_db_params, current_head_version_id):
event = {"action": "create_db"}
response = db_manager.handler(event, None)
assert response["statusCode"] == 200, response["body"]
yield current_head_version_id
drop_hame_db(main_db_params, root_db_params)
@pytest.fixture()
def hame_database_migrated(root_db_params, main_db_params, current_head_version_id):
event = {"action": "migrate_db"}
response = db_manager.handler(event, None)
assert response["statusCode"] == 200, response["body"]
yield current_head_version_id
drop_hame_db(main_db_params, root_db_params)
@pytest.fixture()
def hame_database_migrated_down(hame_database_migrated):
event = {"action": "migrate_db", "version": "base"}
response = db_manager.handler(event, None)
assert response["statusCode"] == 200, response["body"]
yield "base"
def process_revision_directives_remove_empty(context, revision, directives):
# remove migration if it is empty
script = directives[0]
if script.upgrade_ops.is_empty():
directives[:] = []
def process_revision_directives_add_table(context, revision, directives):
# try adding a new table
directives[0] = ops.MigrationScript(
"abcdef12345",
ops.UpgradeOps(
ops=[
ops.CreateTableOp(
"test_table",
[
sqlalchemy.Column("id", sqlalchemy.Integer(), primary_key=True),
sqlalchemy.Column(
"name", sqlalchemy.String(50), nullable=False
),
],
schema="hame",
)
],
),
ops.DowngradeOps(
ops=[ops.DropTableOp("test_table", schema="hame")],
),
)
@pytest.fixture()
def autogenerated_migration(
alembic_cfg, hame_database_migrated, current_head_version_id
):
revision = command.revision(
alembic_cfg,
message="Test migration",
head=current_head_version_id,
autogenerate=True,
process_revision_directives=process_revision_directives_remove_empty,
)
path = Path(revision.path) if revision else None
yield path
if path:
path.unlink()
@pytest.fixture()
def new_migration(alembic_cfg, hame_database_migrated, current_head_version_id):
revision = command.revision(
alembic_cfg,
message="Test migration",
head=current_head_version_id,
autogenerate=True,
process_revision_directives=process_revision_directives_add_table,
)
path = Path(revision.path)
assert path.is_file()
new_head_version_id = revision.revision
yield new_head_version_id
path.unlink()
@pytest.fixture()
def hame_database_upgraded(new_migration):
event = {"action": "migrate_db"}
response = db_manager.handler(event, None)
assert response["statusCode"] == 200, response["body"]
yield new_migration
@pytest.fixture()
def hame_database_downgraded(hame_database_upgraded, current_head_version_id):
event = {"action": "migrate_db", "version": current_head_version_id}
response = db_manager.handler(event, None)
assert response["statusCode"] == 200, response["body"]
yield current_head_version_id
def drop_hame_db(main_db_params, root_db_params):
conn = psycopg2.connect(**root_db_params)
try:
conn.autocommit = True
with conn.cursor() as cur:
cur.execute(
f"DROP DATABASE IF EXISTS {main_db_params['dbname']} WITH (FORCE)"
)
for user in os.environ.get("DB_USERS").split(","):
cur.execute(f"DROP ROLE IF EXISTS {user}")
finally:
conn.close()
def wait_until_responsive(check, timeout, pause, clock=timeit.default_timer):
"""
Wait until a service is responsive.
Taken from docker_services.wait_until_responsive
"""
ref = clock()
now = ref
while (now - ref) < timeout:
if check():
return
time.sleep(pause)
now = clock()
raise Exception("Timeout reached while waiting on service!")
def is_responsive(params):
succeeds = False
try:
with psycopg2.connect(**params):
succeeds = True
except psycopg2.OperationalError:
pass
return succeeds
def assert_database_is_alright(
cur: psycopg2.extensions.cursor,
expected_hame_count: int = hame_count,
expected_codes_count: int = codes_count,
expected_matview_count: int = matview_count,
):
"""
Checks that the database has the right amount of tables with the right
permissions.
"""
# Check schemas
cur.execute(
"SELECT schema_name FROM information_schema.schemata WHERE schema_name IN ('hame', 'codes') ORDER BY schema_name DESC"
)
assert cur.fetchall() == [("hame",), ("codes",)]
# Check users
hame_users = os.environ.get("DB_USERS", "").split(",")
cur.execute("SELECT rolname FROM pg_roles")
assert set(hame_users).issubset({row[0] for row in cur.fetchall()})
# Check schema permissions
for user in hame_users:
cur.execute(f"SELECT has_schema_privilege('{user}', 'hame', 'usage')")
assert cur.fetchall() == [(True,)]
cur.execute(f"SELECT has_schema_privilege('{user}', 'codes', 'usage')")
assert cur.fetchall() == [(True,)]
# Check hame tables
cur.execute("SELECT tablename, tableowner FROM pg_tables WHERE schemaname='hame';")
hame_tables = cur.fetchall()
assert len(hame_tables) == expected_hame_count
for table in hame_tables:
table_name = table[0]
owner = table[1]
# Check table owner and read permissions
assert owner == os.environ.get("SU_USER", "")
cur.execute(
f"SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_schema = 'hame' AND table_name='{table_name}';"
)
grants = cur.fetchall()
assert (os.environ.get("R_USER"), "SELECT") in grants
assert (os.environ.get("R_USER"), "INSERT") not in grants
assert (os.environ.get("R_USER"), "UPDATE") not in grants
assert (os.environ.get("R_USER"), "DELETE") not in grants
assert (os.environ.get("RW_USER"), "SELECT") in grants
assert (os.environ.get("RW_USER"), "INSERT") in grants
assert (os.environ.get("RW_USER"), "UPDATE") in grants
assert (os.environ.get("RW_USER"), "DELETE") in grants
assert (os.environ.get("ADMIN_USER"), "SELECT") in grants
assert (os.environ.get("ADMIN_USER"), "INSERT") in grants
assert (os.environ.get("ADMIN_USER"), "UPDATE") in grants
assert (os.environ.get("ADMIN_USER"), "DELETE") in grants
# Check indexes
cur.execute(
f"SELECT indexdef FROM pg_indexes WHERE schemaname = 'hame' AND tablename = '{table_name}';"
)
index_defs = [index_def for (index_def,) in cur]
cur.execute(
f"SELECT column_name FROM information_schema.columns WHERE table_schema = 'hame' AND table_name = '{table_name}';"
)
columns = [column for (column,) in cur]
if "id" in columns:
assert (
f"CREATE UNIQUE INDEX {table_name}_pkey ON hame.{table_name} USING btree (id)"
in index_defs
)
if "geom" in columns:
assert (
f"CREATE INDEX idx_{table_name}_geom ON hame.{table_name} USING gist (geom)"
in index_defs
)
# Check ordering index, all ordering columns should have an index
if "ordering" in columns:
if table_name == "plan_regulation_group":
assert (
"CREATE INDEX ix_plan_regulation_group_plan_id_ordering "
"ON hame.plan_regulation_group USING btree (plan_id, ordering)"
) in index_defs
elif table_name in ("plan_regulation", "plan_proposition"):
assert (
f"CREATE UNIQUE INDEX ix_{table_name}_plan_regulation_group_id_ordering "
f"ON hame.{table_name} USING btree (plan_regulation_group_id, ordering)"
) in index_defs
elif table_name in (
"land_use_area",
"other_area",
"line",
"land_use_point",
"other_point",
):
assert (
f"CREATE UNIQUE INDEX ix_{table_name}_plan_id_ordering "
f"ON hame.{table_name} USING btree (plan_id, ordering)"
) in index_defs
# Check code tables
cur.execute("SELECT tablename, tableowner FROM pg_tables WHERE schemaname='codes';")
code_tables = cur.fetchall()
assert len(code_tables) == expected_codes_count
for table in code_tables:
table_name = table[0]
owner = table[1]
# Check table owner and read permissions
assert owner == os.environ.get("SU_USER", "")
cur.execute(
f"SELECT grantee, privilege_type FROM information_schema.role_table_grants WHERE table_schema = 'codes' AND table_name='{table_name}';"
)
grants = cur.fetchall()
assert (os.environ.get("R_USER"), "SELECT") in grants
assert (os.environ.get("R_USER"), "INSERT") not in grants
assert (os.environ.get("R_USER"), "UPDATE") not in grants
assert (os.environ.get("R_USER"), "DELETE") not in grants
assert (os.environ.get("RW_USER"), "SELECT") in grants
assert (os.environ.get("RW_USER"), "INSERT") not in grants
assert (os.environ.get("RW_USER"), "UPDATE") not in grants
assert (os.environ.get("RW_USER"), "DELETE") not in grants
assert (os.environ.get("ADMIN_USER"), "SELECT") in grants
assert (os.environ.get("ADMIN_USER"), "INSERT") in grants
assert (os.environ.get("ADMIN_USER"), "UPDATE") in grants
assert (os.environ.get("ADMIN_USER"), "DELETE") in grants
# Check code indexes
cur.execute(
f"SELECT * FROM pg_indexes WHERE schemaname = 'codes' AND tablename = '{table_name}';"
)
indexes = cur.fetchall()
assert (
"codes",
table_name,
f"{table_name}_pkey",
None,
f"CREATE UNIQUE INDEX {table_name}_pkey ON codes.{table_name} USING btree (id)",
) in indexes
assert (
"codes",
table_name,
f"ix_codes_{table_name}_level",
None,
f"CREATE INDEX ix_codes_{table_name}_level ON codes.{table_name} USING btree (level)",
) in indexes
assert (
"codes",
table_name,
f"ix_codes_{table_name}_parent_id",
None,
f"CREATE INDEX ix_codes_{table_name}_parent_id ON codes.{table_name} USING btree (parent_id)",
) in indexes
assert (
"codes",
table_name,
f"ix_codes_{table_name}_short_name",
None,
f"CREATE INDEX ix_codes_{table_name}_short_name ON codes.{table_name} USING btree (short_name)",
) in indexes
assert (
"codes",
table_name,
f"ix_codes_{table_name}_value",
None,
f"CREATE UNIQUE INDEX ix_codes_{table_name}_value ON codes.{table_name} USING btree (value)",
) in indexes
# TODO: Check materialized views once we have any
# cur.execute(
# "SELECT matviewname, matviewowner FROM pg_matviews WHERE schemaname='kooste';"
# )
# materialized_views = cur.fetchall()
# assert len(materialized_views) == expected_matview_count
# for view in materialized_views:
# view_name = view[0]
# owner = view[1]
# # Check view owner and read permissions
# # Materialized views must be owned by the read_write user so they can be
# updated automatically!
# assert owner == os.environ.get("RW_USER", "")
# # Materialized views permissions are only stored in psql specific tables
# cur.execute(f"SELECT relacl FROM pg_class WHERE relname='{view_name}';")
# permission_string = cur.fetchall()[0][0]
# assert f"{os.environ.get('R_USER')}=r/" in permission_string
# assert f"{os.environ.get('RW_USER')}=arwdDxt/" in permission_string
# assert f"{os.environ.get('ADMIN_USER')}=arwdDxt/" in permission_string
@pytest.fixture(scope="module")
def connection_string(hame_database_created) -> str:
return DatabaseHelper().get_connection_string()
@pytest.fixture(scope="module")
def session(connection_string):
engine = sqlalchemy.create_engine(connection_string)
session = sessionmaker(bind=engine)
yield session()
@pytest.fixture
def rollback_after(session: Session):
yield
session.rollback()
@pytest.fixture()
def code_instance(session):
instance = codes.LifeCycleStatus(value="test", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def another_code_instance(session):
instance = codes.LifeCycleStatus(value="test2", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def preparation_status_instance(session):
instance = codes.LifeCycleStatus(value="03", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def plan_proposal_status_instance(session):
instance = codes.LifeCycleStatus(value="04", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def plan_type_instance(session):
# Let's use real code to allow testing API endpoints that require this
# code value as parameter
# https://koodistot.suomi.fi/codescheme;registryCode=rytj;schemeCode=RY_Kaavalaji
# 11: Kokonaismaakuntakaava
instance = codes.PlanType(value="11", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_underground_instance(session):
instance = codes.TypeOfUnderground(value="01", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_plan_regulation_group_instance(session):
instance = codes.TypeOfPlanRegulationGroup(value="test", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_general_plan_regulation_group_instance(session):
instance = codes.TypeOfPlanRegulationGroup(
value="generalRegulations", status="LOCAL"
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_plan_regulation_instance(session):
instance = codes.TypeOfPlanRegulation(value="asumisenAlue", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_plan_regulation_verbal_instance(session):
instance = codes.TypeOfPlanRegulation(value="sanallinenMaarays", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_verbal_plan_regulation_instance(session):
instance = codes.TypeOfVerbalPlanRegulation(value="perustaminen", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_additional_information_instance(session):
instance = codes.TypeOfAdditionalInformation(
value="paakayttotarkoitus", status="LOCAL"
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_source_data_instance(session):
instance = codes.TypeOfSourceData(value="test", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def type_of_document_instance(session):
instance = codes.TypeOfDocument(value="test", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def category_of_publicity_instance(session):
instance = codes.CategoryOfPublicity(value="test", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def administrative_region_instance(session):
instance = codes.AdministrativeRegion(value="01", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def another_administrative_region_instance(session):
instance = codes.AdministrativeRegion(value="02", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def plan_theme_instance(session):
instance = codes.PlanTheme(value="01", status="LOCAL")
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def plan_instance(
session,
code_instance,
another_code_instance,
preparation_status_instance,
plan_proposal_status_instance,
organisation_instance,
another_organisation_instance,
plan_type_instance,
):
# Any status and organisation instances that may be added to the plan later
# have to be included above. If they are only created later, they will be torn
# down too early and teardown will fail, because plan cannot have empty
# status or organisation.
instance = models.Plan(
geom=from_shape(
shape(
{
"type": "MultiPolygon",
"coordinates": [
[
[
[381849.834412134019658, 6677967.973336197435856],
[381849.834412134019658, 6680613.389312859624624],
[386378.427863708813675, 6680613.389312859624624],
[386378.427863708813675, 6677967.973336197435856],
[381849.834412134019658, 6677967.973336197435856],
]
]
],
}
),
srid=PROJECT_SRID,
extended=True,
),
scale=1,
description={"fin": "test_plan"},
lifecycle_status=preparation_status_instance,
organisation=organisation_instance,
plan_type=plan_type_instance,
to_be_exported=True,
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def another_plan_instance(
session,
code_instance,
another_code_instance,
preparation_status_instance,
plan_proposal_status_instance,
organisation_instance,
another_organisation_instance,
plan_type_instance,
):
# Any status and organisation instances that may be added to the plan later
# have to be included above. If they are only created later, they will be torn
# down too early and teardown will fail, because plan cannot have empty
# status or organisation.
instance = models.Plan(
geom=from_shape(
shape(
{
"type": "MultiPolygon",
"coordinates": [
[
[
[381849.834412134019658, 6677967.973336197435856],
[381849.834412134019658, 6680613.389312859624624],
[386378.427863708813675, 6680613.389312859624624],
[386378.427863708813675, 6677967.973336197435856],
[381849.834412134019658, 6677967.973336197435856],
]
]
],
}
),
srid=PROJECT_SRID,
extended=True,
),
scale=1,
description={"fin": "another_test_plan"},
lifecycle_status=preparation_status_instance,
organisation=organisation_instance,
plan_type=plan_type_instance,
to_be_exported=True,
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def organisation_instance(session, administrative_region_instance):
instance = models.Organisation(
business_id="test", administrative_region=administrative_region_instance
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture()
def another_organisation_instance(session, another_administrative_region_instance):
instance = models.Organisation(
business_id="other-test",
administrative_region=another_administrative_region_instance,
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def land_use_area_instance(
session,
preparation_status_instance,
type_of_underground_instance,
plan_instance,
plan_regulation_group_instance,
):
instance = models.LandUseArea(
geom=from_shape(
shape(
{
"type": "MultiPolygon",
"coordinates": [
[
[
[381849.834412134019658, 6677967.973336197435856],
[381849.834412134019658, 6680613.389312859624624],
[386378.427863708813675, 6680613.389312859624624],
[386378.427863708813675, 6677967.973336197435856],
[381849.834412134019658, 6677967.973336197435856],
]
]
],
}
),
srid=PROJECT_SRID,
extended=True,
),
name={"fin": "test_land_use_area"},
description={"fin": "test_land_use_area"},
height_range=Range(0.0, 1.0),
height_unit="m",
lifecycle_status=preparation_status_instance,
type_of_underground=type_of_underground_instance,
plan=plan_instance,
plan_regulation_groups=[plan_regulation_group_instance],
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def other_area_instance(
session,
preparation_status_instance,
type_of_underground_instance,
plan_instance,
plan_regulation_group_instance,
):
instance = models.OtherArea(
geom=from_shape(
shape(
{
"type": "MultiPolygon",
"coordinates": [
[
[
[381849.834412134019658, 6677967.973336197435856],
[381849.834412134019658, 6680613.389312859624624],
[386378.427863708813675, 6680613.389312859624624],
[386378.427863708813675, 6677967.973336197435856],
[381849.834412134019658, 6677967.973336197435856],
]
]
],
}
),
srid=PROJECT_SRID,
extended=True,
),
lifecycle_status=preparation_status_instance,
type_of_underground=type_of_underground_instance,
plan=plan_instance,
plan_regulation_groups=[plan_regulation_group_instance],
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def line_instance(
session,
preparation_status_instance,
type_of_underground_instance,
plan_instance,
plan_regulation_group_instance,
):
instance = models.Line(
geom=from_shape(
MultiLineString(
[
[[382000, 6678000], [383000, 6678000]],
]
)
),
lifecycle_status=preparation_status_instance,
type_of_underground=type_of_underground_instance,
plan=plan_instance,
plan_regulation_groups=[plan_regulation_group_instance],
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def land_use_point_instance(
session,
preparation_status_instance,
type_of_underground_instance,
plan_instance,
point_plan_regulation_group_instance,
):
instance = models.LandUsePoint(
geom=from_shape(MultiPoint([[382000, 6678000]])),
name={"fin": "test_land_use_point"},
description={"fin": "test_land_use_point"},
lifecycle_status=preparation_status_instance,
type_of_underground=type_of_underground_instance,
plan=plan_instance,
plan_regulation_groups=[point_plan_regulation_group_instance],
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def other_point_instance(
session,
preparation_status_instance,
type_of_underground_instance,
plan_instance,
point_plan_regulation_group_instance,
):
instance = models.OtherPoint(
geom=from_shape(MultiPoint([[382000, 6678000], [383000, 6678000]])),
lifecycle_status=preparation_status_instance,
type_of_underground=type_of_underground_instance,
plan=plan_instance,
plan_regulation_groups=[point_plan_regulation_group_instance],
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def plan_regulation_group_instance(
session, plan_instance, type_of_plan_regulation_group_instance
):
instance = models.PlanRegulationGroup(
short_name="K",
plan=plan_instance,
ordering=2,
type_of_plan_regulation_group=type_of_plan_regulation_group_instance,
name={"fin": "test_plan_regulation_group"},
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def point_plan_regulation_group_instance(
session, plan_instance, type_of_plan_regulation_group_instance
):
instance = models.PlanRegulationGroup(
short_name="L",
plan=plan_instance,
ordering=1,
type_of_plan_regulation_group=type_of_plan_regulation_group_instance,
name={"fin": "test_point_plan_regulation_group"},
)
session.add(instance)
session.commit()
yield instance
session.delete(instance)
session.commit()
@pytest.fixture(scope="function")
def general_regulation_group_instance(
session, plan_instance, type_of_general_plan_regulation_group_instance
):
instance = models.PlanRegulationGroup(
short_name="Y",
plan=plan_instance,