/
test_generate_terraform.py
760 lines (638 loc) · 20.8 KB
/
test_generate_terraform.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
# Copyright 2021 Google LLC
#
# 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.
import pathlib
import random
import re
import shutil
import subprocess
import tempfile
import pytest
from ruamel import yaml
from scripts import generate_terraform
PROJECT_ROOT = generate_terraform.PROJECT_ROOT
SAMPLE_YAML_PATHS = {
"dataset": PROJECT_ROOT / "samples" / "dataset.yaml",
"pipeline": PROJECT_ROOT / "samples" / "pipeline.yaml",
}
ENV_PATH = PROJECT_ROOT / ".test"
ENV_DATASETS_PATH = ENV_PATH / "datasets"
yaml = yaml.YAML(typ="safe")
@pytest.fixture
def dataset_path():
with tempfile.TemporaryDirectory(
dir=generate_terraform.DATASETS_PATH, suffix="_dataset"
) as dir_path:
yield pathlib.Path(dir_path)
@pytest.fixture
def pipeline_path(dataset_path, suffix="_pipeline"):
with tempfile.TemporaryDirectory(dir=dataset_path, suffix=suffix) as dir_path:
yield pathlib.Path(dir_path)
@pytest.fixture
def project_id() -> str:
return "test-gcp-project-id"
@pytest.fixture
def bucket_name_prefix() -> str:
return "1234-zyxwvu"
@pytest.fixture
def region() -> str:
return "us-east4"
@pytest.fixture
def impersonating_acct() -> str:
return "test-impersonator@project.iam.gserviceaccount.com"
@pytest.fixture
def gcs_bucket_resource() -> dict:
return {
"type": "storage_bucket",
"name": "{{ friendly_project_id }}.{{ dataset_id }}",
}
@pytest.fixture
def bq_table_resource() -> dict:
return {
"type": "bigquery_table",
"table_id": "test_bq_table",
"schema": [
{"name": "test_col_string", "type": "STRING"},
{"name": "test_col_int", "type": "INT64"},
{"name": "test_col_numeric", "type": "NUMERIC"},
{"name": "test_col_datetime", "type": "DATETIME"},
{"name": "test_col_struct", "type": "STRUCT"},
],
}
@pytest.fixture
def tf_state_bucket() -> str:
return "test-terraform-state-bucket"
@pytest.fixture
def tf_state_prefix() -> str:
return "test/terraform/state"
@pytest.fixture
def env() -> str:
return "test"
def test_tf_templates_exist():
for _, filepath in generate_terraform.TEMPLATE_PATHS.items():
assert filepath.exists()
def test_main_generates_tf_files(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / "provider.tf").exists()
assert (path_prefix / f"{dataset_path.name}_dataset.tf").exists()
assert (path_prefix / f"{pipeline_path.name}_pipeline.tf").exists()
assert (path_prefix / "variables.tf").exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "terraform.tfvars"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "terraform.tfvars"
).exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "backend.tf"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "backend.tf"
).exists()
def test_main_without_tf_remote_state_generates_tf_files_except_backend_tf(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / "provider.tf").exists()
assert (path_prefix / f"{dataset_path.name}_dataset.tf").exists()
assert (path_prefix / f"{pipeline_path.name}_pipeline.tf").exists()
assert (path_prefix / "variables.tf").exists()
assert not (path_prefix / "backend.tf").exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "terraform.tfvars"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "terraform.tfvars"
).exists()
pipeline_path_2 = pipeline_path
def test_main_with_multiple_pipelines(
dataset_path,
pipeline_path,
pipeline_path_2,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
assert pipeline_path.name != pipeline_path_2.name
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path_2 / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / "provider.tf").exists()
assert (path_prefix / f"{dataset_path.name}_dataset.tf").exists()
assert (path_prefix / f"{pipeline_path.name}_pipeline.tf").exists()
assert (path_prefix / f"{pipeline_path_2.name}_pipeline.tf").exists()
assert (path_prefix / "variables.tf").exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "terraform.tfvars"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "terraform.tfvars"
).exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "backend.tf"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "backend.tf"
).exists()
def test_dataset_without_any_pipelines(
dataset_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / "provider.tf").exists()
assert (path_prefix / f"{dataset_path.name}_dataset.tf").exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "terraform.tfvars"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "terraform.tfvars"
).exists()
assert not (
generate_terraform.DATASETS_PATH
/ dataset_path.name
/ "_terraform"
/ "backend.tf"
).exists()
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "backend.tf"
).exists()
def test_dataset_path_does_not_exist(
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
with pytest.raises(FileNotFoundError):
generate_terraform.main(
"non_existing_dir",
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
def test_generated_tf_files_contain_license_headers(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
license_header = pathlib.Path(
generate_terraform.TEMPLATE_PATHS["license"]
).read_text()
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / "provider.tf").read_text().count(license_header) == 1
assert (path_prefix / f"{dataset_path.name}_dataset.tf").read_text().count(
license_header
) == 1
assert (path_prefix / f"{pipeline_path.name}_pipeline.tf").read_text().count(
license_header
) == 1
assert (path_prefix / "variables.tf").read_text().count(license_header) == 1
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "terraform.tfvars"
).read_text().count(license_header) == 1
assert (
ENV_DATASETS_PATH / dataset_path.name / "_terraform" / "backend.tf"
).read_text().count(license_header) == 1
def test_dataset_tf_file_contains_description_when_specified(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
config = yaml.load(open(dataset_path / "dataset.yaml"))
bq_dataset = next(
(r for r in config["resources"] if r["type"] == "bigquery_dataset"), None
)
assert bq_dataset
assert bq_dataset["description"]
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / f"{dataset_path.name}_dataset.tf").read_text().count(
f"description = \"{bq_dataset['description']}\""
) == 1
def test_dataset_tf_has_no_bq_dataset_description_when_unspecified(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
config = yaml.load(open(dataset_path / "dataset.yaml"))
# Get the first bigquery_dataset resource and delete the `description` field
bq_dataset = next(
(r for r in config["resources"] if r["type"] == "bigquery_dataset")
)
del bq_dataset["description"]
with open(dataset_path / "dataset.yaml", "w") as file:
yaml.dump(config, file)
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
# Match the "google_bigquery_dataset" properties, i.e. any lines between the
# curly braces, in the *_dataset.tf file
regexp = r"\"google_bigquery_dataset\" \"" + dataset_path.name + r"\" \{(.*?)\}"
bq_dataset_tf_string = re.compile(regexp, flags=re.MULTILINE | re.DOTALL)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
result = bq_dataset_tf_string.search(
(path_prefix / f"{dataset_path.name}_dataset.tf").read_text()
)
assert re.search(r"dataset_id\s+\=", result.group(1))
assert not re.search(r"description\s+\=", result.group(1))
def test_pipeline_tf_contains_bq_table_description_when_specified(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
config = yaml.load(open(pipeline_path / "pipeline.yaml"))
bq_table = next(
(r for r in config["resources"] if r["type"] == "bigquery_table"), None
)
assert bq_table
assert bq_table["description"]
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
assert (path_prefix / f"{pipeline_path.name}_pipeline.tf").read_text().count(
f"description = \"{bq_table['description']}\""
) == 1
def test_pipeline_tf_has_no_bq_table_description_when_unspecified(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
config = yaml.load(open(pipeline_path / "pipeline.yaml"))
# Get the first bigquery_table resource and delete the `description` field
bq_table = next(
(r for r in config["resources"] if r["type"] == "bigquery_table"), None
)
del bq_table["description"]
with open(pipeline_path / "pipeline.yaml", "w") as file:
yaml.dump(config, file)
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
# Match the "google_bigquery_table" properties, i.e. any lines between the
# curly braces, in the *_pipeline.tf file
regexp = r"\"google_bigquery_table\" \"" + bq_table["table_id"] + r"\" \{(.*?)\}"
bq_table_tf_string = re.compile(regexp, flags=re.MULTILINE | re.DOTALL)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
result = bq_table_tf_string.search(
(path_prefix / f"{pipeline_path.name}_pipeline.tf").read_text()
)
assert re.search(r"table_id\s+\=", result.group(1))
assert not re.search(r"description\s+\=", result.group(1))
def test_bq_table_name_starts_with_digits_but_tf_resource_name_does_not(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
config = yaml.load(open(pipeline_path / "pipeline.yaml"))
table_name_starting_with_digit = f"{str(random.randint(0, 9))}_table"
# In the YAML config, set the BigQuery table name to start with a digit
bq_table = next(
(r for r in config["resources"] if r["type"] == "bigquery_table"), None
)
bq_table["table_id"] = table_name_starting_with_digit
with open(pipeline_path / "pipeline.yaml", "w") as file:
yaml.dump(config, file)
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
# Match the Terraform resource name and the table_id value in the BigQuery
# table's resource definition. As a concrete example, substrings in
# ALL_CAPS are matched below:
#
# resource "google_bigquery_table" "RESOURCE_NAME_STARTING_WITH_NONDIGIT" {
# description = ""
# table_id = "TABLE_NAME_STARTING_WITH_DIGIT"
# }
tf_resource_regexp = r"\"google_bigquery_table\" \"([a-zA-Z0-9_-]+)\" .*?"
table_id_regexp = r"table_id\s+\= \"(.*?)\"\n"
matcher = re.compile(
tf_resource_regexp + table_id_regexp,
flags=re.MULTILINE | re.DOTALL,
)
for path_prefix in (
ENV_DATASETS_PATH / dataset_path.name / "_terraform",
generate_terraform.DATASETS_PATH / dataset_path.name / "_terraform",
):
result = matcher.search(
(path_prefix / f"{pipeline_path.name}_pipeline.tf").read_text()
)
tf_resource_name = result.group(1)
table_id = result.group(2)
assert table_id == table_name_starting_with_digit
assert not tf_resource_name[0].isdigit()
assert table_id[0].isdigit()
assert table_id in tf_resource_name
def test_bucket_names_must_not_contain_dots_and_google():
for name in (
"test.bucket.name",
"google-bucket",
"google.bucket.name",
"g00gle",
"googl3",
):
with pytest.raises(ValueError):
generate_terraform.validate_bucket_name(name)
def test_bucket_names_must_use_hyphens_instead_of_underscores():
for name in (
"test_underscore",
"test-bucket_with-underscore",
):
with pytest.raises(ValueError):
generate_terraform.validate_bucket_name(name)
def test_bucket_prefixes_must_use_hyphens_instead_of_underscores(
dataset_path,
project_id,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
):
for prefix in (
"test_prefix",
"test-hyphens_and_underscores",
):
with pytest.raises(ValueError):
generate_terraform.main(
dataset_path.name,
project_id,
prefix,
region,
impersonating_acct,
env,
tf_state_bucket,
tf_state_prefix,
)
def test_validation_on_generated_tf_files_in_dot_env_dir(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
env_dataset_path = ENV_DATASETS_PATH / dataset_path.name
subprocess.check_call(["terraform", "init"], cwd=env_dataset_path / "_terraform")
subprocess.check_call(
["terraform", "validate"], cwd=env_dataset_path / "_terraform"
)
def test_validation_on_generated_tf_files_in_project_dir(
dataset_path,
pipeline_path,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
):
shutil.copyfile(SAMPLE_YAML_PATHS["dataset"], dataset_path / "dataset.yaml")
shutil.copyfile(SAMPLE_YAML_PATHS["pipeline"], pipeline_path / "pipeline.yaml")
generate_terraform.main(
dataset_path.name,
project_id,
bucket_name_prefix,
region,
impersonating_acct,
env,
None,
None,
)
project_dataset_path = generate_terraform.DATASETS_PATH / dataset_path.name
subprocess.check_call(
["terraform", "init"], cwd=(project_dataset_path / "_terraform")
)
subprocess.check_call(
["terraform", "validate"], cwd=(project_dataset_path / "_terraform")
)