summaryrefslogtreecommitdiff
path: root/python-dtspec.spec
blob: 34d67eca40ce331f35f0d488d5d88432a4293688 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
%global _empty_manifest_terminate_build 0
Name:		python-dtspec
Version:	0.7.5
Release:	1
Summary:	dtspec - Data Test Spec
License:	MIT
URL:		https://github.com/inside-track/dtspec
Source0:	https://mirrors.aliyun.com/pypi/web/packages/38/94/ebc9c6bf397744ec6bfad655cd2c298cbb4dd573ce98bd5a1150699a7d09/dtspec-0.7.5.tar.gz
BuildArch:	noarch


%description
version: '0.1'
description: HelloWorld - Simplest example of running dtspec
# The names of sources and targets is arbitrary, but it's up to the user to determine
# how they get mapped to/from their data transformation system.
sources:
  - source: raw_students
targets:
  - target: salutations
````
These define our inputs and outputs.  But we also need to define how to generate
data for the input(s).  For that, we define a **factory**:
````yaml
factories:
  - factory: SomeStudents
    description: Minimal example of what some student records may look like
    data:
      - source: raw_students
        # Tables written as a markdown table
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
Lastly, we need to describe how we expect the data to look after it has been transformed.
To do this, we define **scenarios** and **cases**.  Scenarios are collections of cases
that share some common data factory or describe similar situations.  For now, our
transform spec will just contain a single scenario and a single case:
````yaml
scenarios:
  - scenario: Hello World
    description: The simplest scenario
    # All cases in this scenario will use this factory (which may be modified on case-by-case basis)
    factory:
        parents:
          - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              # The actual output may also contain the "name" field, but the expectation
              # will ignore comparing any fields not listed in the expected table.
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
That's it. See also the [full YAML spec](tests/hello_world.yml).
Now that we've described the full transform spec, we need to use it.  The first step is to
parse the YAML file, send it to the dtspec api, and have dtspec generate source data:
````python
import dtspec
import yaml
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
````
The specific steps taken at this point are going to be sensitive to the data transformation
environment being used, but we'll stick with our Pandas transformations for the sake of this
tutorial.  Given this, we can define a simple function that converts the source data returned
from dtspec into Pandas dataframes:
````python
import pandas as pd
def parse_sources(sources):
    "Converts test data returned from dtspec api into Pandas dataframes"
    return {
        source_name: pd.DataFrame.from_records(data.serialize())
        for source_name, data in sources.items()
    }
````
We can then run those test Pandas dataframes through our data transformation function.
````python
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
````
Next, we need to convert the output dataframes of the transformations, `actual_data`,
back into a format that can be loaded into dtspec for comparison.  For Pandas,
this function is:
````python
def serialize_actuals(actuals):
    "Converts Pandas dataframe results into form needed to load dtspec api actuals"
    return {
        target_name: json.loads(dataframe.astype(str).to_json(orient="records"))
        for target_name, dataframe in actuals.items()
    }
````
It is loaded into dtspec using:
````python
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Finally, dtspec can be called to run all of the expectations:
````python
api.assert_expectations()
````
Putting all of this together:
````python
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Try running the above code and changing either the YAML spec or the `hello_world_transformer`
function and see how dtspec responds.
### Hello World With Multiple Test Cases
Running tests with multiple cases that reference the same data sources
introduces a complicating factor. One of the reasons that makes
it hard to build tests for ETL/ELT is the fact that many data
transformation systems in use today have a high latency for even very
small transformations.  For example, Redshift is a distributed RDBMS
that can process billions of rows in minutes, millions of rows in
seconds, thousands of rows in seconds, or 10s of rows in, well,
seconds.  Given these latency issues, we don't want to have to rely on
loading data into our system, running a test, clearing out the data,
loading some more, running the next test, and so on as is often
done when testing ORM-based applications like Rails or Django.
dtspec seeks to minimize the number of requests on the data
transformation system in order to deal with these latency issues.
It does this by "stacking" the test data generated in each case
and delivering back to the user all of this stacked data.  The user
then loads this stacked data into their data transformation system
**once**, runs the data transformations **once**, and then collects
the resulting output **once**.
Let's see how dtspec handles this in action.
First, let's change our hello world data transformation a bit.  Instead of
just saying hello to our heroes, let's say goodbye to any villians (as
identified by a `clique` data field).
````python
def hello_world_multiple_transformer(raw_students):
    def salutation(row):
        if row["clique"] == "Scooby Gang":
            return "Hello {}".format(row["name"])
        return "Goodbye {}".format(row["name"])
    salutations_df = raw_students.copy()
    salutations_df["salutation"] = salutations_df.apply(salutation, axis=1)
    return {"salutations": salutations_df}
````
While it would be possible to test saying hello or goodbye in a single
case just by adding more records to the source data, we'll split it
into two to demonstrate how multiple cases work.  Here's how the YAML would look:
````yaml
scenarios:
  - scenario: Hello World With Multiple Cases
    description: The simplest scenario
    factory:
      parents:
        - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation   |
                | -  | -      | -           | -            |
                | 1  | Buffy  | Scooby Gang | Hello Buffy  |
                | 2  | Willow | Scooby Gang | Hello Willow |
      - case: GoodbyeVillians
        description: Say goodbye to villians
        # For this case, we tweak the factory defined for the scenario.
        factory:
          # The ids here might be the same as above.  However, these are just named
          # references and get translated into unique ids when the source data
          # is generated.
          data:
            - source: raw_students
              table: |
                | id | name     |
                | -  | -        |
                | 1  | Drusilla |
                | 2  | Harmony  |
              # Use values to populate a constant over all records
              values:
                - column: clique
                  value: Vampires
        expected:
          data:
            # Again, the ids here are not the actual ids sent to dtspec after performing
            # the transformations.  They are just named references and dtspec
            # keeps track of the relationship between the actual ids and the named ones.
            - target: salutations
              table: |
                | id | name     | clique   | salutation       |
                | -  | -        | -        | -                |
                | 1  | Drusilla | Vampires | Goodbye Drusilla |
                | 2  | Harmony  | Vampires | Goodbye Harmony  |
````
This won't quite work as is, because we're missing something.  We have
two cases that describe variations on the source data `raw_students`
and the output `salutations`.  dtspec collects the source data
definitions from each case and stacks them into a single data source.
The user then runs the transformations on that source and generates a
single target to provide back to dtspec.  But dtspec has to know which record
belongs to which case.  To do this, we have to define an
**identifier** that tells dtspec which columns should be used to identify
a record as belonging to a case.  A good identifier is often a primary
key that uniquely defines a record, but it is not strictly required to
be unique across all records.
For this example, we'll define an identifier called "students" with a single
**identifier attribute** called `id` that is a unique integer:
````yaml
identifiers:
  - identifier: students
    attributes:
      - field: id
        generator: unique_integer
````
We tell dtspec that this identifier is associated with the `id` columns of both
the source and the target via:
````yaml
sources:
  - source: raw_students
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
targets:
  - target: salutations
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
````
With the sources and targets with identifiers, the values we see in
the source factories and target expectations are not the values that
are actually used in the data.  Instead, they are simply **named
refereces**.  For example, in the "HelloGang" case, `id=1` belongs to
Buffy and `id=2` belongs to Willow.  But when dtspec generates the source
data, the actual values may be 3 and 9, or 4 and 7, or something else.
Unique values are not generated in any deterministic manner -- each
run of dtspec can give a diferent set.  dtspec only guarantees that the
each named reference will be a unique integer (via the `generator`
defined in the `identifier` section).
Futhermore, in the second case called "GoodbyeVillians", we see that
`id=1` belongs to Drusilla and `id=2` belongs to Harmony.  dtspec will
generate unique values for this case as well, and they **will not**
conflict with the values generated for the first case.  So dtspec will pass
back to the user 4 total records (Buffy, Willow, Drusilla, Harmony) with 4
different ids
With the [full YAML spec](tests/hello_world_multiple_cases.yml) defined, we can
run the assertions in the same fashion as the the earlier example
````python
spec = yaml.safe_load(open("tests/hello_world_multiple_cases.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
#### Embedded Identifiers
It is also possible to embed identifiers in the value of a particular column.
For example, suppose our `salutation` column said hello to the `id` instead
of the name of the person.  To make this work, we have to put a particular
string pattern in the column that indicates the name of the identifier, the
attribute, and the named id - `{identifier.attribute[named_id]}`.  The
yaml spec would look like:
````yaml
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation             |
                | -  | -      | -           | -                      |
                | 1  | Buffy  | Scooby Gang | Hello {students.id[1]} |
                | 2  | Willow | Scooby Gang | Hello {students.id[2]} |
````
The [realistic example](tests/realistic.yml) discussed below has another example
of using embedded identifiers.
**Note** that embedded identifiers cannot be used to associate records
with cases.  A target must have at least one column listed in the
`identifier_map` section.
### A More Realistic Example
Finally, let's example a more realistic example that one might
encounter when building a data warehouse.  In these situations, we'll
have multiple sources, targets, scenarios, and cases.  Now suppose we
have a students table, where every student belongs to a school and
takes 0 to many classes.  Our goal is to create one denormalized table
that combines all of these data sources into one table.  Additionally,
we want to create a table that aggregates all of our students to give
a count of the students per school.  In Pandas, the data transformation
might look like:
````python
def realistic_transformer(raw_students, raw_schools, raw_classes, dim_date):
    student_schools = raw_students.rename(
        columns={"id": "student_id", "external_id": "card_id"}
    ).merge(
        raw_schools.rename(columns={"id": "school_id", "name": "school_name"}),
        how="inner",
        on="school_id",
    )
    student_classes = student_schools.merge(
        raw_classes.rename(columns={"name": "class_name"}),
        how="inner",
        on="student_id",
    ).merge(
        dim_date.rename(columns={"date": "start_date"}), how="left", on="start_date"
    )
    student_classes["student_class_id"] = student_classes.apply(
        lambda row: "-".join([str(row["card_id"]), str(row["class_name"])]), axis=1
    )
    students_per_school = (
        student_schools.groupby(["school_name"])
        .size()
        .to_frame(name="number_of_students")
        .reset_index()
    )
    return {
        "student_classes": student_classes,
        "students_per_school": students_per_school,
    }
````
Given the [full YAML spec](tests/realistic.yml) defined, we can again run
the data assertions using a familiar pattern:
````python
spec = yaml.safe_load(open("tests/realistic.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
## dbt support
dtspec also contains a CLI tool that can facilitate using it with [dbt](https://getdbt.com).
The CLI tools helps you set up a test environment, run dbt in that environment, and
execute the dbt tests.  The CLI tool currently only works for Postgres and Snowflake dbt
projects.
See the [dbt-container-skeleton](https://github.com/gnilrets/dbt-container-skeleton) for a
working example.
### dtspec CLI Config
All of the dtspec files should be placed in a subdirectory of your dbt project: `dbt/dtspec`.
The first thing to set up for the dtspec CLI is the configuration file, which should
be placed in `dtspec/config.yml`.  The configuration file tells dtspec how to recreate
the table schemas in a test environment, where to recreate the table schemas, and where
to find the results of a dbt run.  Here is an example:
````yaml
# A target environment is where the output of data transformations appear.
# Typically, there will only be on target environment.
target_environments:
  # The target environment IS NOT your production environment.  It needs to be a separate
  # database where dbt will run against the test data that dtspec generates.  The name
  # of this environment needs to be the same as a target defined in dbt profiles.yml (in this case `dtspec`)
  dtspec:
    # Field names here follow the same conventions as dbt profiles.yml (https://docs.getdbt.com/dbt-cli/configure-your-profile)
    type: postgres
    host: "{{ env_var('POSTGRES_HOST') }}"
    port: 5432
    user: "{{ env_var('POSTGRES_USER') }}"
    password: "{{ env_var('POSTGRES_PASSWORD') }}"
    dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
# A source environment is where source data is located.  It may be in the same database
# as the target environment or it may be different if the data warehouse supports it (e.g., Snowflake).
# It is also possible to define several source environments if your source data is spread
# across multiple databases.
source_environments:
  raw:
    # Use `tables` to specify source tables that need to be present to run tests.
    tables:
      # `wh_raw` is the name of a namespace (aka schema) in the `raw` source environment
      wh_raw:
        # tables may be listed indivdually (or, use `wh_raw: '*'` to indicate all tables within the `wh_raw` namespace)
        - raw_customers
        - raw_orders
        - raw_payments
    # In order to run tests, we need to replicate the table schemas in the test environment.
    # The schema section here contains credentials for a database where those tables are defined.
    # This is likely a production database (in your warehouse), or is a production replica.
    # dtspec only uses this database to read reflect the table schemas (via `dtspec db --fetch-schemas`).
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    # The test section contains credentials for a database where test data will be created.
    # Data in this database is destroyed and rebuilt for every run of dtspec and SHOULD NOT be
    # the same as the schema credentials defined above.
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
  # Pretending snapshots are in a different database because Postgres doesn't support cross-db queries.
  # This is how you would do it if snapshots were in a different database than other raw source data.
  snapshots:
    tables:
      snapshots: '*'
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
````
### Test environment setup
Once the configuration file has been defined, the next step is to fetch/reflect schemas for
the source tables.  From the `dbt` directory, run the following CLI command:
    dtspec db --fetch-schemas
This will query all of the databases defined in the `schema` section of the source
environments defined in `dtspec/config.yml`, and create table schema files in `dtspec/schemas`.
The files in this directory should be committed to source control and updated whenever
your source data changes (in so much as it would affect the dtspec tests).
Next, initialize the test databases defined in the `test` section of the source
environments defined in `dtspec/config.yml` with the CLI command
    dtspec db --init-test-db
This will create empty source tables in your test databases, ready to be loaded with test data.
### Executing tests
In order to use dtspec with dbt, spec files must make use of the `dbt_source` and `dbt_ref`
Jinja functions.  These are analogous to the dbt `source` and `ref` functions.  dtspec
will compile your dbt project and use the `dbt/target/manifest.json` file to resolve the names
of sources and targets that you want to test.  For example, the SomeStudents factory
would be written as follows if this were a dbt project:
````yaml
factories:
  - factory: SomeStudents
    data:
      - source: {{ dbt_source('raw', 'raw_students') }}
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
and an expectation would be:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
With these references set, dtspec tests can be executed via the CLI command:
    dtspec test-dbt
This command will do the following:
1. It will first compile your dbt project.  If your dbt code does not change between
   dtspec tests, you may skip this step by pass the `--partial-parse` argument.
2. The dtspec spec files are compiled into a single document and dbt references are resolved.
   The compiled dtspec document is output to `dtspec/compiled_specs.yml`, which does not
   need to be saved to source control.
3. Source data is generated and loaded into the test databases.
4. dbt is executed against the test database.
5. The models that dbt built in the target test environment are extracted.  These are the "actuals".
6. The actuals are compared with the expected data as specified in the dtspec specs.
The `test-dbt` command has several options that may be useful.  See `dtspec test-dbt -h` for a full
list, but here are some noteworthy options:
- `--models` specifies the models that dbt should run, using standard dbt model selection syntax.
- `--scenarios` is used to restrict the number of scenarios that are tested.  The argument is a
  regular expression that will match on the compiled Scenario name.  This can be used
  in combination with the `--models` command to only run those tests and models that you're
  concerned with.
### Additonal CLI notes
#### Log level
If you want to see more detailed loggin information, set the `DTSPEC_LOG_LEVEL` environment
variable (options are DEBUG, INFO, WARN, and ERROR).  For example:
    DTSPEC_LOG_LEVEL=INFO dtspec test-dbt
#### Project location
If you really don't want to put dtspec in the dbt project directory you can override the
default by setting `DTSPEC_ROOT` and `DBT_ROOT` environment variables that point
to the root path of these projects.
#### Special Values
When dtspec is run via the CLI, it recognizes nulls and booleans in the spec files.  To
indicate these kinds of values in a dtspec spec, use `{NULL}`, `{True}`, and `{False}`.
For example:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   | is_witch |
                | -  | -            | -        |
                | 1  | Hello Buffy  | {False}  |
                | 2  | Hello Willow | {True}   |
                | 3  | Hello NA     | {NULL}   |
````
#### Jinja context
When writing spec files that will be parsed with the dtspec CLI, the following functions
are available in the jinja context:
* `datetime` -- This is the [Python datetime.datetime type](https://docs.python.org/3/library/datetime.html)
* `date` -- This is the [Python datetime.date type](https://docs.python.org/3/library/datetime.html)
* `relativedelta` -- This is the [Python relativedelta type0](https://dateutil.readthedocs.io/en/stable/relativedelta.html)
* `UTCNOW` -- The UTC datetime value at the time the specs are parsed
* `TODAY` -- The current UTC date value at the time the specs are parsed
* `YESTERDAY` -- Yesterday's date
* `TOMORROW` -- Tomorrow's date
* `dbt_source` -- Used to reference dbt sources
* `dbt_ref` -- Used to reference dbt models
Some example of using these functions:
    - source: raw_products
       table: |
        | export_time                          | file                    | product_id | product_name |
        | -                                    | -                       | -          | -            |
        | {{ YESTERDAY }}                      | products-2021-01-06.csv | milk       | Milk         |
        | {{ TODAY - relativedelta(days=5) }}  | products-2021-01-02.csv | milk       | Milk         |
## Additional notes about dtspec
* At the moment, all source data values are generated as strings.  It
  is up to the the user to enforce data types suitable to their data
  transformation system.  Note that the dtspec dbt CLI commands handle this
  for Postgres and Snowflake warehouses.
* Additionally, data expectations are stringified prior to running assertions.
## Contributing
We welcome contributors!  Please submit any suggests or pull requests in Github.
### Developer setup
Create an appropriate python environment.  I like [miniconda](https://conda.io/miniconda.html),
but use whatever you like:
    conda create --name dtspec python=3.8
    conda activate dtspec
Then install pip packages
    pip install pip-tools
    pip install --ignore-installed -r requirements.txt
run tests via
    inv test
and the linter via
    inv lint

%package -n python3-dtspec
Summary:	dtspec - Data Test Spec
Provides:	python-dtspec
BuildRequires:	python3-devel
BuildRequires:	python3-setuptools
BuildRequires:	python3-pip
%description -n python3-dtspec
version: '0.1'
description: HelloWorld - Simplest example of running dtspec
# The names of sources and targets is arbitrary, but it's up to the user to determine
# how they get mapped to/from their data transformation system.
sources:
  - source: raw_students
targets:
  - target: salutations
````
These define our inputs and outputs.  But we also need to define how to generate
data for the input(s).  For that, we define a **factory**:
````yaml
factories:
  - factory: SomeStudents
    description: Minimal example of what some student records may look like
    data:
      - source: raw_students
        # Tables written as a markdown table
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
Lastly, we need to describe how we expect the data to look after it has been transformed.
To do this, we define **scenarios** and **cases**.  Scenarios are collections of cases
that share some common data factory or describe similar situations.  For now, our
transform spec will just contain a single scenario and a single case:
````yaml
scenarios:
  - scenario: Hello World
    description: The simplest scenario
    # All cases in this scenario will use this factory (which may be modified on case-by-case basis)
    factory:
        parents:
          - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              # The actual output may also contain the "name" field, but the expectation
              # will ignore comparing any fields not listed in the expected table.
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
That's it. See also the [full YAML spec](tests/hello_world.yml).
Now that we've described the full transform spec, we need to use it.  The first step is to
parse the YAML file, send it to the dtspec api, and have dtspec generate source data:
````python
import dtspec
import yaml
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
````
The specific steps taken at this point are going to be sensitive to the data transformation
environment being used, but we'll stick with our Pandas transformations for the sake of this
tutorial.  Given this, we can define a simple function that converts the source data returned
from dtspec into Pandas dataframes:
````python
import pandas as pd
def parse_sources(sources):
    "Converts test data returned from dtspec api into Pandas dataframes"
    return {
        source_name: pd.DataFrame.from_records(data.serialize())
        for source_name, data in sources.items()
    }
````
We can then run those test Pandas dataframes through our data transformation function.
````python
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
````
Next, we need to convert the output dataframes of the transformations, `actual_data`,
back into a format that can be loaded into dtspec for comparison.  For Pandas,
this function is:
````python
def serialize_actuals(actuals):
    "Converts Pandas dataframe results into form needed to load dtspec api actuals"
    return {
        target_name: json.loads(dataframe.astype(str).to_json(orient="records"))
        for target_name, dataframe in actuals.items()
    }
````
It is loaded into dtspec using:
````python
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Finally, dtspec can be called to run all of the expectations:
````python
api.assert_expectations()
````
Putting all of this together:
````python
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Try running the above code and changing either the YAML spec or the `hello_world_transformer`
function and see how dtspec responds.
### Hello World With Multiple Test Cases
Running tests with multiple cases that reference the same data sources
introduces a complicating factor. One of the reasons that makes
it hard to build tests for ETL/ELT is the fact that many data
transformation systems in use today have a high latency for even very
small transformations.  For example, Redshift is a distributed RDBMS
that can process billions of rows in minutes, millions of rows in
seconds, thousands of rows in seconds, or 10s of rows in, well,
seconds.  Given these latency issues, we don't want to have to rely on
loading data into our system, running a test, clearing out the data,
loading some more, running the next test, and so on as is often
done when testing ORM-based applications like Rails or Django.
dtspec seeks to minimize the number of requests on the data
transformation system in order to deal with these latency issues.
It does this by "stacking" the test data generated in each case
and delivering back to the user all of this stacked data.  The user
then loads this stacked data into their data transformation system
**once**, runs the data transformations **once**, and then collects
the resulting output **once**.
Let's see how dtspec handles this in action.
First, let's change our hello world data transformation a bit.  Instead of
just saying hello to our heroes, let's say goodbye to any villians (as
identified by a `clique` data field).
````python
def hello_world_multiple_transformer(raw_students):
    def salutation(row):
        if row["clique"] == "Scooby Gang":
            return "Hello {}".format(row["name"])
        return "Goodbye {}".format(row["name"])
    salutations_df = raw_students.copy()
    salutations_df["salutation"] = salutations_df.apply(salutation, axis=1)
    return {"salutations": salutations_df}
````
While it would be possible to test saying hello or goodbye in a single
case just by adding more records to the source data, we'll split it
into two to demonstrate how multiple cases work.  Here's how the YAML would look:
````yaml
scenarios:
  - scenario: Hello World With Multiple Cases
    description: The simplest scenario
    factory:
      parents:
        - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation   |
                | -  | -      | -           | -            |
                | 1  | Buffy  | Scooby Gang | Hello Buffy  |
                | 2  | Willow | Scooby Gang | Hello Willow |
      - case: GoodbyeVillians
        description: Say goodbye to villians
        # For this case, we tweak the factory defined for the scenario.
        factory:
          # The ids here might be the same as above.  However, these are just named
          # references and get translated into unique ids when the source data
          # is generated.
          data:
            - source: raw_students
              table: |
                | id | name     |
                | -  | -        |
                | 1  | Drusilla |
                | 2  | Harmony  |
              # Use values to populate a constant over all records
              values:
                - column: clique
                  value: Vampires
        expected:
          data:
            # Again, the ids here are not the actual ids sent to dtspec after performing
            # the transformations.  They are just named references and dtspec
            # keeps track of the relationship between the actual ids and the named ones.
            - target: salutations
              table: |
                | id | name     | clique   | salutation       |
                | -  | -        | -        | -                |
                | 1  | Drusilla | Vampires | Goodbye Drusilla |
                | 2  | Harmony  | Vampires | Goodbye Harmony  |
````
This won't quite work as is, because we're missing something.  We have
two cases that describe variations on the source data `raw_students`
and the output `salutations`.  dtspec collects the source data
definitions from each case and stacks them into a single data source.
The user then runs the transformations on that source and generates a
single target to provide back to dtspec.  But dtspec has to know which record
belongs to which case.  To do this, we have to define an
**identifier** that tells dtspec which columns should be used to identify
a record as belonging to a case.  A good identifier is often a primary
key that uniquely defines a record, but it is not strictly required to
be unique across all records.
For this example, we'll define an identifier called "students" with a single
**identifier attribute** called `id` that is a unique integer:
````yaml
identifiers:
  - identifier: students
    attributes:
      - field: id
        generator: unique_integer
````
We tell dtspec that this identifier is associated with the `id` columns of both
the source and the target via:
````yaml
sources:
  - source: raw_students
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
targets:
  - target: salutations
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
````
With the sources and targets with identifiers, the values we see in
the source factories and target expectations are not the values that
are actually used in the data.  Instead, they are simply **named
refereces**.  For example, in the "HelloGang" case, `id=1` belongs to
Buffy and `id=2` belongs to Willow.  But when dtspec generates the source
data, the actual values may be 3 and 9, or 4 and 7, or something else.
Unique values are not generated in any deterministic manner -- each
run of dtspec can give a diferent set.  dtspec only guarantees that the
each named reference will be a unique integer (via the `generator`
defined in the `identifier` section).
Futhermore, in the second case called "GoodbyeVillians", we see that
`id=1` belongs to Drusilla and `id=2` belongs to Harmony.  dtspec will
generate unique values for this case as well, and they **will not**
conflict with the values generated for the first case.  So dtspec will pass
back to the user 4 total records (Buffy, Willow, Drusilla, Harmony) with 4
different ids
With the [full YAML spec](tests/hello_world_multiple_cases.yml) defined, we can
run the assertions in the same fashion as the the earlier example
````python
spec = yaml.safe_load(open("tests/hello_world_multiple_cases.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
#### Embedded Identifiers
It is also possible to embed identifiers in the value of a particular column.
For example, suppose our `salutation` column said hello to the `id` instead
of the name of the person.  To make this work, we have to put a particular
string pattern in the column that indicates the name of the identifier, the
attribute, and the named id - `{identifier.attribute[named_id]}`.  The
yaml spec would look like:
````yaml
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation             |
                | -  | -      | -           | -                      |
                | 1  | Buffy  | Scooby Gang | Hello {students.id[1]} |
                | 2  | Willow | Scooby Gang | Hello {students.id[2]} |
````
The [realistic example](tests/realistic.yml) discussed below has another example
of using embedded identifiers.
**Note** that embedded identifiers cannot be used to associate records
with cases.  A target must have at least one column listed in the
`identifier_map` section.
### A More Realistic Example
Finally, let's example a more realistic example that one might
encounter when building a data warehouse.  In these situations, we'll
have multiple sources, targets, scenarios, and cases.  Now suppose we
have a students table, where every student belongs to a school and
takes 0 to many classes.  Our goal is to create one denormalized table
that combines all of these data sources into one table.  Additionally,
we want to create a table that aggregates all of our students to give
a count of the students per school.  In Pandas, the data transformation
might look like:
````python
def realistic_transformer(raw_students, raw_schools, raw_classes, dim_date):
    student_schools = raw_students.rename(
        columns={"id": "student_id", "external_id": "card_id"}
    ).merge(
        raw_schools.rename(columns={"id": "school_id", "name": "school_name"}),
        how="inner",
        on="school_id",
    )
    student_classes = student_schools.merge(
        raw_classes.rename(columns={"name": "class_name"}),
        how="inner",
        on="student_id",
    ).merge(
        dim_date.rename(columns={"date": "start_date"}), how="left", on="start_date"
    )
    student_classes["student_class_id"] = student_classes.apply(
        lambda row: "-".join([str(row["card_id"]), str(row["class_name"])]), axis=1
    )
    students_per_school = (
        student_schools.groupby(["school_name"])
        .size()
        .to_frame(name="number_of_students")
        .reset_index()
    )
    return {
        "student_classes": student_classes,
        "students_per_school": students_per_school,
    }
````
Given the [full YAML spec](tests/realistic.yml) defined, we can again run
the data assertions using a familiar pattern:
````python
spec = yaml.safe_load(open("tests/realistic.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
## dbt support
dtspec also contains a CLI tool that can facilitate using it with [dbt](https://getdbt.com).
The CLI tools helps you set up a test environment, run dbt in that environment, and
execute the dbt tests.  The CLI tool currently only works for Postgres and Snowflake dbt
projects.
See the [dbt-container-skeleton](https://github.com/gnilrets/dbt-container-skeleton) for a
working example.
### dtspec CLI Config
All of the dtspec files should be placed in a subdirectory of your dbt project: `dbt/dtspec`.
The first thing to set up for the dtspec CLI is the configuration file, which should
be placed in `dtspec/config.yml`.  The configuration file tells dtspec how to recreate
the table schemas in a test environment, where to recreate the table schemas, and where
to find the results of a dbt run.  Here is an example:
````yaml
# A target environment is where the output of data transformations appear.
# Typically, there will only be on target environment.
target_environments:
  # The target environment IS NOT your production environment.  It needs to be a separate
  # database where dbt will run against the test data that dtspec generates.  The name
  # of this environment needs to be the same as a target defined in dbt profiles.yml (in this case `dtspec`)
  dtspec:
    # Field names here follow the same conventions as dbt profiles.yml (https://docs.getdbt.com/dbt-cli/configure-your-profile)
    type: postgres
    host: "{{ env_var('POSTGRES_HOST') }}"
    port: 5432
    user: "{{ env_var('POSTGRES_USER') }}"
    password: "{{ env_var('POSTGRES_PASSWORD') }}"
    dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
# A source environment is where source data is located.  It may be in the same database
# as the target environment or it may be different if the data warehouse supports it (e.g., Snowflake).
# It is also possible to define several source environments if your source data is spread
# across multiple databases.
source_environments:
  raw:
    # Use `tables` to specify source tables that need to be present to run tests.
    tables:
      # `wh_raw` is the name of a namespace (aka schema) in the `raw` source environment
      wh_raw:
        # tables may be listed indivdually (or, use `wh_raw: '*'` to indicate all tables within the `wh_raw` namespace)
        - raw_customers
        - raw_orders
        - raw_payments
    # In order to run tests, we need to replicate the table schemas in the test environment.
    # The schema section here contains credentials for a database where those tables are defined.
    # This is likely a production database (in your warehouse), or is a production replica.
    # dtspec only uses this database to read reflect the table schemas (via `dtspec db --fetch-schemas`).
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    # The test section contains credentials for a database where test data will be created.
    # Data in this database is destroyed and rebuilt for every run of dtspec and SHOULD NOT be
    # the same as the schema credentials defined above.
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
  # Pretending snapshots are in a different database because Postgres doesn't support cross-db queries.
  # This is how you would do it if snapshots were in a different database than other raw source data.
  snapshots:
    tables:
      snapshots: '*'
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
````
### Test environment setup
Once the configuration file has been defined, the next step is to fetch/reflect schemas for
the source tables.  From the `dbt` directory, run the following CLI command:
    dtspec db --fetch-schemas
This will query all of the databases defined in the `schema` section of the source
environments defined in `dtspec/config.yml`, and create table schema files in `dtspec/schemas`.
The files in this directory should be committed to source control and updated whenever
your source data changes (in so much as it would affect the dtspec tests).
Next, initialize the test databases defined in the `test` section of the source
environments defined in `dtspec/config.yml` with the CLI command
    dtspec db --init-test-db
This will create empty source tables in your test databases, ready to be loaded with test data.
### Executing tests
In order to use dtspec with dbt, spec files must make use of the `dbt_source` and `dbt_ref`
Jinja functions.  These are analogous to the dbt `source` and `ref` functions.  dtspec
will compile your dbt project and use the `dbt/target/manifest.json` file to resolve the names
of sources and targets that you want to test.  For example, the SomeStudents factory
would be written as follows if this were a dbt project:
````yaml
factories:
  - factory: SomeStudents
    data:
      - source: {{ dbt_source('raw', 'raw_students') }}
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
and an expectation would be:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
With these references set, dtspec tests can be executed via the CLI command:
    dtspec test-dbt
This command will do the following:
1. It will first compile your dbt project.  If your dbt code does not change between
   dtspec tests, you may skip this step by pass the `--partial-parse` argument.
2. The dtspec spec files are compiled into a single document and dbt references are resolved.
   The compiled dtspec document is output to `dtspec/compiled_specs.yml`, which does not
   need to be saved to source control.
3. Source data is generated and loaded into the test databases.
4. dbt is executed against the test database.
5. The models that dbt built in the target test environment are extracted.  These are the "actuals".
6. The actuals are compared with the expected data as specified in the dtspec specs.
The `test-dbt` command has several options that may be useful.  See `dtspec test-dbt -h` for a full
list, but here are some noteworthy options:
- `--models` specifies the models that dbt should run, using standard dbt model selection syntax.
- `--scenarios` is used to restrict the number of scenarios that are tested.  The argument is a
  regular expression that will match on the compiled Scenario name.  This can be used
  in combination with the `--models` command to only run those tests and models that you're
  concerned with.
### Additonal CLI notes
#### Log level
If you want to see more detailed loggin information, set the `DTSPEC_LOG_LEVEL` environment
variable (options are DEBUG, INFO, WARN, and ERROR).  For example:
    DTSPEC_LOG_LEVEL=INFO dtspec test-dbt
#### Project location
If you really don't want to put dtspec in the dbt project directory you can override the
default by setting `DTSPEC_ROOT` and `DBT_ROOT` environment variables that point
to the root path of these projects.
#### Special Values
When dtspec is run via the CLI, it recognizes nulls and booleans in the spec files.  To
indicate these kinds of values in a dtspec spec, use `{NULL}`, `{True}`, and `{False}`.
For example:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   | is_witch |
                | -  | -            | -        |
                | 1  | Hello Buffy  | {False}  |
                | 2  | Hello Willow | {True}   |
                | 3  | Hello NA     | {NULL}   |
````
#### Jinja context
When writing spec files that will be parsed with the dtspec CLI, the following functions
are available in the jinja context:
* `datetime` -- This is the [Python datetime.datetime type](https://docs.python.org/3/library/datetime.html)
* `date` -- This is the [Python datetime.date type](https://docs.python.org/3/library/datetime.html)
* `relativedelta` -- This is the [Python relativedelta type0](https://dateutil.readthedocs.io/en/stable/relativedelta.html)
* `UTCNOW` -- The UTC datetime value at the time the specs are parsed
* `TODAY` -- The current UTC date value at the time the specs are parsed
* `YESTERDAY` -- Yesterday's date
* `TOMORROW` -- Tomorrow's date
* `dbt_source` -- Used to reference dbt sources
* `dbt_ref` -- Used to reference dbt models
Some example of using these functions:
    - source: raw_products
       table: |
        | export_time                          | file                    | product_id | product_name |
        | -                                    | -                       | -          | -            |
        | {{ YESTERDAY }}                      | products-2021-01-06.csv | milk       | Milk         |
        | {{ TODAY - relativedelta(days=5) }}  | products-2021-01-02.csv | milk       | Milk         |
## Additional notes about dtspec
* At the moment, all source data values are generated as strings.  It
  is up to the the user to enforce data types suitable to their data
  transformation system.  Note that the dtspec dbt CLI commands handle this
  for Postgres and Snowflake warehouses.
* Additionally, data expectations are stringified prior to running assertions.
## Contributing
We welcome contributors!  Please submit any suggests or pull requests in Github.
### Developer setup
Create an appropriate python environment.  I like [miniconda](https://conda.io/miniconda.html),
but use whatever you like:
    conda create --name dtspec python=3.8
    conda activate dtspec
Then install pip packages
    pip install pip-tools
    pip install --ignore-installed -r requirements.txt
run tests via
    inv test
and the linter via
    inv lint

%package help
Summary:	Development documents and examples for dtspec
Provides:	python3-dtspec-doc
%description help
version: '0.1'
description: HelloWorld - Simplest example of running dtspec
# The names of sources and targets is arbitrary, but it's up to the user to determine
# how they get mapped to/from their data transformation system.
sources:
  - source: raw_students
targets:
  - target: salutations
````
These define our inputs and outputs.  But we also need to define how to generate
data for the input(s).  For that, we define a **factory**:
````yaml
factories:
  - factory: SomeStudents
    description: Minimal example of what some student records may look like
    data:
      - source: raw_students
        # Tables written as a markdown table
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
Lastly, we need to describe how we expect the data to look after it has been transformed.
To do this, we define **scenarios** and **cases**.  Scenarios are collections of cases
that share some common data factory or describe similar situations.  For now, our
transform spec will just contain a single scenario and a single case:
````yaml
scenarios:
  - scenario: Hello World
    description: The simplest scenario
    # All cases in this scenario will use this factory (which may be modified on case-by-case basis)
    factory:
        parents:
          - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              # The actual output may also contain the "name" field, but the expectation
              # will ignore comparing any fields not listed in the expected table.
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
That's it. See also the [full YAML spec](tests/hello_world.yml).
Now that we've described the full transform spec, we need to use it.  The first step is to
parse the YAML file, send it to the dtspec api, and have dtspec generate source data:
````python
import dtspec
import yaml
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
````
The specific steps taken at this point are going to be sensitive to the data transformation
environment being used, but we'll stick with our Pandas transformations for the sake of this
tutorial.  Given this, we can define a simple function that converts the source data returned
from dtspec into Pandas dataframes:
````python
import pandas as pd
def parse_sources(sources):
    "Converts test data returned from dtspec api into Pandas dataframes"
    return {
        source_name: pd.DataFrame.from_records(data.serialize())
        for source_name, data in sources.items()
    }
````
We can then run those test Pandas dataframes through our data transformation function.
````python
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
````
Next, we need to convert the output dataframes of the transformations, `actual_data`,
back into a format that can be loaded into dtspec for comparison.  For Pandas,
this function is:
````python
def serialize_actuals(actuals):
    "Converts Pandas dataframe results into form needed to load dtspec api actuals"
    return {
        target_name: json.loads(dataframe.astype(str).to_json(orient="records"))
        for target_name, dataframe in actuals.items()
    }
````
It is loaded into dtspec using:
````python
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Finally, dtspec can be called to run all of the expectations:
````python
api.assert_expectations()
````
Putting all of this together:
````python
spec = yaml.safe_load(open("tests/hello_world.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
````
Try running the above code and changing either the YAML spec or the `hello_world_transformer`
function and see how dtspec responds.
### Hello World With Multiple Test Cases
Running tests with multiple cases that reference the same data sources
introduces a complicating factor. One of the reasons that makes
it hard to build tests for ETL/ELT is the fact that many data
transformation systems in use today have a high latency for even very
small transformations.  For example, Redshift is a distributed RDBMS
that can process billions of rows in minutes, millions of rows in
seconds, thousands of rows in seconds, or 10s of rows in, well,
seconds.  Given these latency issues, we don't want to have to rely on
loading data into our system, running a test, clearing out the data,
loading some more, running the next test, and so on as is often
done when testing ORM-based applications like Rails or Django.
dtspec seeks to minimize the number of requests on the data
transformation system in order to deal with these latency issues.
It does this by "stacking" the test data generated in each case
and delivering back to the user all of this stacked data.  The user
then loads this stacked data into their data transformation system
**once**, runs the data transformations **once**, and then collects
the resulting output **once**.
Let's see how dtspec handles this in action.
First, let's change our hello world data transformation a bit.  Instead of
just saying hello to our heroes, let's say goodbye to any villians (as
identified by a `clique` data field).
````python
def hello_world_multiple_transformer(raw_students):
    def salutation(row):
        if row["clique"] == "Scooby Gang":
            return "Hello {}".format(row["name"])
        return "Goodbye {}".format(row["name"])
    salutations_df = raw_students.copy()
    salutations_df["salutation"] = salutations_df.apply(salutation, axis=1)
    return {"salutations": salutations_df}
````
While it would be possible to test saying hello or goodbye in a single
case just by adding more records to the source data, we'll split it
into two to demonstrate how multiple cases work.  Here's how the YAML would look:
````yaml
scenarios:
  - scenario: Hello World With Multiple Cases
    description: The simplest scenario
    factory:
      parents:
        - SomeStudents
    cases:
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation   |
                | -  | -      | -           | -            |
                | 1  | Buffy  | Scooby Gang | Hello Buffy  |
                | 2  | Willow | Scooby Gang | Hello Willow |
      - case: GoodbyeVillians
        description: Say goodbye to villians
        # For this case, we tweak the factory defined for the scenario.
        factory:
          # The ids here might be the same as above.  However, these are just named
          # references and get translated into unique ids when the source data
          # is generated.
          data:
            - source: raw_students
              table: |
                | id | name     |
                | -  | -        |
                | 1  | Drusilla |
                | 2  | Harmony  |
              # Use values to populate a constant over all records
              values:
                - column: clique
                  value: Vampires
        expected:
          data:
            # Again, the ids here are not the actual ids sent to dtspec after performing
            # the transformations.  They are just named references and dtspec
            # keeps track of the relationship between the actual ids and the named ones.
            - target: salutations
              table: |
                | id | name     | clique   | salutation       |
                | -  | -        | -        | -                |
                | 1  | Drusilla | Vampires | Goodbye Drusilla |
                | 2  | Harmony  | Vampires | Goodbye Harmony  |
````
This won't quite work as is, because we're missing something.  We have
two cases that describe variations on the source data `raw_students`
and the output `salutations`.  dtspec collects the source data
definitions from each case and stacks them into a single data source.
The user then runs the transformations on that source and generates a
single target to provide back to dtspec.  But dtspec has to know which record
belongs to which case.  To do this, we have to define an
**identifier** that tells dtspec which columns should be used to identify
a record as belonging to a case.  A good identifier is often a primary
key that uniquely defines a record, but it is not strictly required to
be unique across all records.
For this example, we'll define an identifier called "students" with a single
**identifier attribute** called `id` that is a unique integer:
````yaml
identifiers:
  - identifier: students
    attributes:
      - field: id
        generator: unique_integer
````
We tell dtspec that this identifier is associated with the `id` columns of both
the source and the target via:
````yaml
sources:
  - source: raw_students
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
targets:
  - target: salutations
    identifier_map:
      - column: id
        identifier:
          name: students
          attribute: id
````
With the sources and targets with identifiers, the values we see in
the source factories and target expectations are not the values that
are actually used in the data.  Instead, they are simply **named
refereces**.  For example, in the "HelloGang" case, `id=1` belongs to
Buffy and `id=2` belongs to Willow.  But when dtspec generates the source
data, the actual values may be 3 and 9, or 4 and 7, or something else.
Unique values are not generated in any deterministic manner -- each
run of dtspec can give a diferent set.  dtspec only guarantees that the
each named reference will be a unique integer (via the `generator`
defined in the `identifier` section).
Futhermore, in the second case called "GoodbyeVillians", we see that
`id=1` belongs to Drusilla and `id=2` belongs to Harmony.  dtspec will
generate unique values for this case as well, and they **will not**
conflict with the values generated for the first case.  So dtspec will pass
back to the user 4 total records (Buffy, Willow, Drusilla, Harmony) with 4
different ids
With the [full YAML spec](tests/hello_world_multiple_cases.yml) defined, we can
run the assertions in the same fashion as the the earlier example
````python
spec = yaml.safe_load(open("tests/hello_world_multiple_cases.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
#### Embedded Identifiers
It is also possible to embed identifiers in the value of a particular column.
For example, suppose our `salutation` column said hello to the `id` instead
of the name of the person.  To make this work, we have to put a particular
string pattern in the column that indicates the name of the identifier, the
attribute, and the named id - `{identifier.attribute[named_id]}`.  The
yaml spec would look like:
````yaml
      - case: HelloGang
        description: Make sure we say hello to everyone
        expected:
          data:
            - target: salutations
              table: |
                | id | name   | clique      | salutation             |
                | -  | -      | -           | -                      |
                | 1  | Buffy  | Scooby Gang | Hello {students.id[1]} |
                | 2  | Willow | Scooby Gang | Hello {students.id[2]} |
````
The [realistic example](tests/realistic.yml) discussed below has another example
of using embedded identifiers.
**Note** that embedded identifiers cannot be used to associate records
with cases.  A target must have at least one column listed in the
`identifier_map` section.
### A More Realistic Example
Finally, let's example a more realistic example that one might
encounter when building a data warehouse.  In these situations, we'll
have multiple sources, targets, scenarios, and cases.  Now suppose we
have a students table, where every student belongs to a school and
takes 0 to many classes.  Our goal is to create one denormalized table
that combines all of these data sources into one table.  Additionally,
we want to create a table that aggregates all of our students to give
a count of the students per school.  In Pandas, the data transformation
might look like:
````python
def realistic_transformer(raw_students, raw_schools, raw_classes, dim_date):
    student_schools = raw_students.rename(
        columns={"id": "student_id", "external_id": "card_id"}
    ).merge(
        raw_schools.rename(columns={"id": "school_id", "name": "school_name"}),
        how="inner",
        on="school_id",
    )
    student_classes = student_schools.merge(
        raw_classes.rename(columns={"name": "class_name"}),
        how="inner",
        on="student_id",
    ).merge(
        dim_date.rename(columns={"date": "start_date"}), how="left", on="start_date"
    )
    student_classes["student_class_id"] = student_classes.apply(
        lambda row: "-".join([str(row["card_id"]), str(row["class_name"])]), axis=1
    )
    students_per_school = (
        student_schools.groupby(["school_name"])
        .size()
        .to_frame(name="number_of_students")
        .reset_index()
    )
    return {
        "student_classes": student_classes,
        "students_per_school": students_per_school,
    }
````
Given the [full YAML spec](tests/realistic.yml) defined, we can again run
the data assertions using a familiar pattern:
````python
spec = yaml.safe_load(open("tests/realistic.yml"))
api = dtspec.api.Api(spec)
api.generate_sources()
sources_data = parse_sources(api.spec["sources"])
actual_data = hello_world_multiple_transformer(**sources_data)
serialized_actuals = serialize_actuals(actual_data)
api.load_actuals(serialized_actuals)
api.assert_expectations()
````
## dbt support
dtspec also contains a CLI tool that can facilitate using it with [dbt](https://getdbt.com).
The CLI tools helps you set up a test environment, run dbt in that environment, and
execute the dbt tests.  The CLI tool currently only works for Postgres and Snowflake dbt
projects.
See the [dbt-container-skeleton](https://github.com/gnilrets/dbt-container-skeleton) for a
working example.
### dtspec CLI Config
All of the dtspec files should be placed in a subdirectory of your dbt project: `dbt/dtspec`.
The first thing to set up for the dtspec CLI is the configuration file, which should
be placed in `dtspec/config.yml`.  The configuration file tells dtspec how to recreate
the table schemas in a test environment, where to recreate the table schemas, and where
to find the results of a dbt run.  Here is an example:
````yaml
# A target environment is where the output of data transformations appear.
# Typically, there will only be on target environment.
target_environments:
  # The target environment IS NOT your production environment.  It needs to be a separate
  # database where dbt will run against the test data that dtspec generates.  The name
  # of this environment needs to be the same as a target defined in dbt profiles.yml (in this case `dtspec`)
  dtspec:
    # Field names here follow the same conventions as dbt profiles.yml (https://docs.getdbt.com/dbt-cli/configure-your-profile)
    type: postgres
    host: "{{ env_var('POSTGRES_HOST') }}"
    port: 5432
    user: "{{ env_var('POSTGRES_USER') }}"
    password: "{{ env_var('POSTGRES_PASSWORD') }}"
    dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
# A source environment is where source data is located.  It may be in the same database
# as the target environment or it may be different if the data warehouse supports it (e.g., Snowflake).
# It is also possible to define several source environments if your source data is spread
# across multiple databases.
source_environments:
  raw:
    # Use `tables` to specify source tables that need to be present to run tests.
    tables:
      # `wh_raw` is the name of a namespace (aka schema) in the `raw` source environment
      wh_raw:
        # tables may be listed indivdually (or, use `wh_raw: '*'` to indicate all tables within the `wh_raw` namespace)
        - raw_customers
        - raw_orders
        - raw_payments
    # In order to run tests, we need to replicate the table schemas in the test environment.
    # The schema section here contains credentials for a database where those tables are defined.
    # This is likely a production database (in your warehouse), or is a production replica.
    # dtspec only uses this database to read reflect the table schemas (via `dtspec db --fetch-schemas`).
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    # The test section contains credentials for a database where test data will be created.
    # Data in this database is destroyed and rebuilt for every run of dtspec and SHOULD NOT be
    # the same as the schema credentials defined above.
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
  # Pretending snapshots are in a different database because Postgres doesn't support cross-db queries.
  # This is how you would do it if snapshots were in a different database than other raw source data.
  snapshots:
    tables:
      snapshots: '*'
    schema:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}"
    test:
      type: postgres
      host: "{{ env_var('POSTGRES_HOST') }}"
      port: 5432
      user: "{{ env_var('POSTGRES_USER') }}"
      password: "{{ env_var('POSTGRES_PASSWORD') }}"
      dbname: "{{ env_var('POSTGRES_DBNAME') }}_dtspec"
````
### Test environment setup
Once the configuration file has been defined, the next step is to fetch/reflect schemas for
the source tables.  From the `dbt` directory, run the following CLI command:
    dtspec db --fetch-schemas
This will query all of the databases defined in the `schema` section of the source
environments defined in `dtspec/config.yml`, and create table schema files in `dtspec/schemas`.
The files in this directory should be committed to source control and updated whenever
your source data changes (in so much as it would affect the dtspec tests).
Next, initialize the test databases defined in the `test` section of the source
environments defined in `dtspec/config.yml` with the CLI command
    dtspec db --init-test-db
This will create empty source tables in your test databases, ready to be loaded with test data.
### Executing tests
In order to use dtspec with dbt, spec files must make use of the `dbt_source` and `dbt_ref`
Jinja functions.  These are analogous to the dbt `source` and `ref` functions.  dtspec
will compile your dbt project and use the `dbt/target/manifest.json` file to resolve the names
of sources and targets that you want to test.  For example, the SomeStudents factory
would be written as follows if this were a dbt project:
````yaml
factories:
  - factory: SomeStudents
    data:
      - source: {{ dbt_source('raw', 'raw_students') }}
        table: |
          | id | name   |
          | -  | -      |
          | 1  | Buffy  |
          | 2  | Willow |
````
and an expectation would be:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   |
                | -  | -            |
                | 1  | Hello Buffy  |
                | 2  | Hello Willow |
````
With these references set, dtspec tests can be executed via the CLI command:
    dtspec test-dbt
This command will do the following:
1. It will first compile your dbt project.  If your dbt code does not change between
   dtspec tests, you may skip this step by pass the `--partial-parse` argument.
2. The dtspec spec files are compiled into a single document and dbt references are resolved.
   The compiled dtspec document is output to `dtspec/compiled_specs.yml`, which does not
   need to be saved to source control.
3. Source data is generated and loaded into the test databases.
4. dbt is executed against the test database.
5. The models that dbt built in the target test environment are extracted.  These are the "actuals".
6. The actuals are compared with the expected data as specified in the dtspec specs.
The `test-dbt` command has several options that may be useful.  See `dtspec test-dbt -h` for a full
list, but here are some noteworthy options:
- `--models` specifies the models that dbt should run, using standard dbt model selection syntax.
- `--scenarios` is used to restrict the number of scenarios that are tested.  The argument is a
  regular expression that will match on the compiled Scenario name.  This can be used
  in combination with the `--models` command to only run those tests and models that you're
  concerned with.
### Additonal CLI notes
#### Log level
If you want to see more detailed loggin information, set the `DTSPEC_LOG_LEVEL` environment
variable (options are DEBUG, INFO, WARN, and ERROR).  For example:
    DTSPEC_LOG_LEVEL=INFO dtspec test-dbt
#### Project location
If you really don't want to put dtspec in the dbt project directory you can override the
default by setting `DTSPEC_ROOT` and `DBT_ROOT` environment variables that point
to the root path of these projects.
#### Special Values
When dtspec is run via the CLI, it recognizes nulls and booleans in the spec files.  To
indicate these kinds of values in a dtspec spec, use `{NULL}`, `{True}`, and `{False}`.
For example:
````yaml
    cases:
      - case: HelloGang
        expected:
          data:
            - target: {{ dbt_ref('salutations') }}
              table: |
                | id | salutation   | is_witch |
                | -  | -            | -        |
                | 1  | Hello Buffy  | {False}  |
                | 2  | Hello Willow | {True}   |
                | 3  | Hello NA     | {NULL}   |
````
#### Jinja context
When writing spec files that will be parsed with the dtspec CLI, the following functions
are available in the jinja context:
* `datetime` -- This is the [Python datetime.datetime type](https://docs.python.org/3/library/datetime.html)
* `date` -- This is the [Python datetime.date type](https://docs.python.org/3/library/datetime.html)
* `relativedelta` -- This is the [Python relativedelta type0](https://dateutil.readthedocs.io/en/stable/relativedelta.html)
* `UTCNOW` -- The UTC datetime value at the time the specs are parsed
* `TODAY` -- The current UTC date value at the time the specs are parsed
* `YESTERDAY` -- Yesterday's date
* `TOMORROW` -- Tomorrow's date
* `dbt_source` -- Used to reference dbt sources
* `dbt_ref` -- Used to reference dbt models
Some example of using these functions:
    - source: raw_products
       table: |
        | export_time                          | file                    | product_id | product_name |
        | -                                    | -                       | -          | -            |
        | {{ YESTERDAY }}                      | products-2021-01-06.csv | milk       | Milk         |
        | {{ TODAY - relativedelta(days=5) }}  | products-2021-01-02.csv | milk       | Milk         |
## Additional notes about dtspec
* At the moment, all source data values are generated as strings.  It
  is up to the the user to enforce data types suitable to their data
  transformation system.  Note that the dtspec dbt CLI commands handle this
  for Postgres and Snowflake warehouses.
* Additionally, data expectations are stringified prior to running assertions.
## Contributing
We welcome contributors!  Please submit any suggests or pull requests in Github.
### Developer setup
Create an appropriate python environment.  I like [miniconda](https://conda.io/miniconda.html),
but use whatever you like:
    conda create --name dtspec python=3.8
    conda activate dtspec
Then install pip packages
    pip install pip-tools
    pip install --ignore-installed -r requirements.txt
run tests via
    inv test
and the linter via
    inv lint

%prep
%autosetup -n dtspec-0.7.5

%build
%py3_build

%install
%py3_install
install -d -m755 %{buildroot}/%{_pkgdocdir}
if [ -d doc ]; then cp -arf doc %{buildroot}/%{_pkgdocdir}; fi
if [ -d docs ]; then cp -arf docs %{buildroot}/%{_pkgdocdir}; fi
if [ -d example ]; then cp -arf example %{buildroot}/%{_pkgdocdir}; fi
if [ -d examples ]; then cp -arf examples %{buildroot}/%{_pkgdocdir}; fi
pushd %{buildroot}
if [ -d usr/lib ]; then
	find usr/lib -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/lib64 ]; then
	find usr/lib64 -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/bin ]; then
	find usr/bin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
if [ -d usr/sbin ]; then
	find usr/sbin -type f -printf "\"/%h/%f\"\n" >> filelist.lst
fi
touch doclist.lst
if [ -d usr/share/man ]; then
	find usr/share/man -type f -printf "\"/%h/%f.gz\"\n" >> doclist.lst
fi
popd
mv %{buildroot}/filelist.lst .
mv %{buildroot}/doclist.lst .

%files -n python3-dtspec -f filelist.lst
%dir %{python3_sitelib}/*

%files help -f doclist.lst
%{_docdir}/*

%changelog
* Fri Jun 09 2023 Python_Bot <Python_Bot@openeuler.org> - 0.7.5-1
- Package Spec generated