-
-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy pathapp.test.ts
1202 lines (1096 loc) · 41.4 KB
/
app.test.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { google } from "googleapis"
import { beforeAll, jest } from "@jest/globals"
// Mock the google docs api to retrieve files from the test-files directory
// AFAICT, we have to do this directly after the import
// and before any other code that might import googleapis
jest.mock("googleapis", () => {
const originalModule: any = jest.requireActual("googleapis")
return {
...originalModule,
google: {
...originalModule.google,
docs: jest.fn(() => ({
documents: {
get: jest.fn(({ documentId }) => {
// This is a bit hacky and assumes we are running from inside
// the itsJustJavascript directory - I couldn't find a better way
// to get the workspace root directory here
const unparsed = fs.readFileSync(
path.join(
__dirname,
"..",
"..",
"adminSiteServer",
"test-files",
`${documentId}.json`
),
"utf8"
)
const data = JSON.parse(unparsed)
return Promise.resolve(data)
}),
},
})),
},
}
})
import { OwidAdminApp } from "./appClass.js"
import { logInAsUser } from "./authentication.js"
import { Knex, knex } from "knex"
import { dbTestConfig } from "../db/tests/dbTestConfig.js"
import {
TransactionCloseMode,
getBestBreadcrumbs,
getParentTagArraysByChildName,
knexReadWriteTransaction,
knexReadonlyTransaction,
setKnexInstance,
} from "../db/db.js"
import { cleanTestDb, TABLES_IN_USE } from "../db/tests/testHelpers.js"
import {
ChartConfigsTableName,
ChartsTableName,
DatasetsTableName,
DbInsertTag,
DbInsertTagGraphNode,
MultiDimDataPagesTableName,
MultiDimXChartConfigsTableName,
TagsTableName,
TagGraphTableName,
VariablesTableName,
TagGraphRootName,
PostsGdocsTableName,
OwidGdocType,
DbInsertPostGdoc,
DbInsertPostGdocXTag,
PostsGdocsXTagsTableName,
} from "@ourworldindata/types"
import path from "path"
import fs from "fs"
import { omitUndefinedValues } from "@ourworldindata/utils"
import { latestGrapherConfigSchema } from "@ourworldindata/grapher"
const ADMIN_SERVER_HOST = "localhost"
const ADMIN_SERVER_PORT = 8765
const ADMIN_URL = `http://${ADMIN_SERVER_HOST}:${ADMIN_SERVER_PORT}/admin/api`
jest.setTimeout(10000) // wait for up to 10s for the app server to start
let testKnexInstance: Knex<any, unknown[]> | undefined = undefined
let serverKnexInstance: Knex<any, unknown[]> | undefined = undefined
let app: OwidAdminApp | undefined = undefined
let cookieId: string = ""
beforeAll(async () => {
// dummy use of google docs so that when we import the google
// docs above to mock it, prettier will not complain about an unused import
const _ = google.docs
testKnexInstance = knex(dbTestConfig)
serverKnexInstance = knex(dbTestConfig)
const dataSpec = {
users: [
{
email: "[email protected]",
fullName: "Admin",
password: "admin",
createdAt: new Date(),
updatedAt: new Date(),
},
],
}
await cleanTestDb(testKnexInstance)
for (const [tableName, tableData] of Object.entries(dataSpec)) {
await testKnexInstance(tableName).insert(tableData)
}
setKnexInstance(serverKnexInstance!)
app = new OwidAdminApp({
isDev: true,
isTest: true,
gitCmsDir: "",
quiet: true,
})
await app.startListening(ADMIN_SERVER_PORT, ADMIN_SERVER_HOST)
cookieId = (
await logInAsUser({
email: "[email protected]",
id: 1,
})
).id
})
async function cleanupDb() {
// We leave the user in the database for other tests to use
// For other cases it is good to drop any rows created in the test
const tables = TABLES_IN_USE.filter((table) => table !== "users")
await knexReadWriteTransaction(
async (trx) => {
for (const table of tables) {
await trx.raw(`DELETE FROM ??`, [table])
}
},
TransactionCloseMode.KeepOpen,
testKnexInstance
)
}
afterEach(async () => {
await cleanupDb()
})
afterAll((done: any) => {
void cleanupDb()
.then(() =>
Promise.allSettled([
app?.stopListening(),
testKnexInstance?.destroy(),
serverKnexInstance?.destroy(),
])
)
.then(() => done())
})
async function getCountForTable(tableName: string): Promise<number> {
// This helper simply checks how many rows are in a table. I can be used
// for super simple asserts to verify if a row was created or deleted.
const count = await testKnexInstance!.table(tableName).count()
return count[0]["count(*)"] as number
}
async function fetchJsonFromAdminApi(path: string) {
const url = ADMIN_URL + path
const response = await fetch(url, {
headers: { cookie: `sessionid=${cookieId}` },
})
expect(response.status).toBe(200)
return await response.json()
}
async function makeRequestAgainstAdminApi(
{
method,
path,
body,
}: {
method: "POST" | "PUT" | "DELETE"
path: string
body?: string
},
{ verifySuccess = true }: { verifySuccess?: boolean } = {}
) {
const url = ADMIN_URL + path
const response = await fetch(url, {
method,
headers: {
"Content-Type": "application/json",
cookie: `sessionid=${cookieId}`,
},
body,
})
expect(response.status).toBe(200)
const json = await response.json()
if (verifySuccess) {
expect(json.success).toBe(true)
}
return json
}
describe("OwidAdminApp", () => {
const testChartConfig = {
$schema: latestGrapherConfigSchema,
slug: "test-chart",
title: "Test chart",
chartTypes: ["LineChart"],
}
it("should be able to create an app", () => {
expect(app).toBeTruthy()
expect(app!.server).toBeTruthy()
})
it("should be able to fetch the version from the server", async () => {
const nodeVersion = await fetch(
"http://localhost:8765/admin/nodeVersion",
{
headers: { cookie: `sessionid=${cookieId}` },
}
)
expect(nodeVersion.status).toBe(200)
const text = await nodeVersion.text()
expect(text).toBe("v22.13.0")
})
it("should be able to edit a chart via the api", async () => {
// make sure the database is in a clean state
const chartCount = await getCountForTable(ChartsTableName)
expect(chartCount).toBe(0)
const chartConfigsCount = await getCountForTable(ChartConfigsTableName)
expect(chartConfigsCount).toBe(0)
const chartId = 1 // since the chart is the first to be inserted
// make a request to create a chart
const response = await makeRequestAgainstAdminApi({
method: "POST",
path: "/charts",
body: JSON.stringify(testChartConfig),
})
expect(response.chartId).toBe(chartId)
// check that a row in the charts table has been added
const chartCountAfter = await getCountForTable(ChartsTableName)
expect(chartCountAfter).toBe(1)
// check that a row in the chart_configs table has been added
const chartConfigsCountAfter = await getCountForTable(
ChartConfigsTableName
)
expect(chartConfigsCountAfter).toBe(1)
// fetch the parent config and verify there is none
const parentConfig = (
await fetchJsonFromAdminApi(`/charts/${chartId}.parent.json`)
)?.config
expect(parentConfig).toBeUndefined()
// fetch the full config and verify that id, version and isPublished are added
const fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfig).toEqual({
...testChartConfig,
id: chartId, // must match the db id
version: 1, // automatically added
isPublished: false, // automatically added
})
// fetch the patch config and verify it's identical to the full config
const patchConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.patchConfig.json`
)
expect(patchConfig).toEqual(fullConfig)
})
it("should be able to create a GDoc article", async () => {
const gdocId = "gdoc-test-create-1"
const response = await makeRequestAgainstAdminApi(
{
method: "PUT",
path: `/gdocs/${gdocId}`,
},
{ verifySuccess: false }
)
expect(response.id).toBe(gdocId)
// Fetch the GDoc to verify it was created
const gdoc = await fetchJsonFromAdminApi(`/gdocs/${gdocId}`)
expect(gdoc.id).toBe(gdocId)
expect(gdoc.content.title).toBe("Basic article")
})
})
describe("OwidAdminApp: indicator-level chart configs", () => {
const variableId = 1
const otherVariableId = 2
const dummyDataset = {
id: 1,
name: "Dummy dataset",
description: "Dataset description",
namespace: "owid",
createdByUserId: 1,
metadataEditedAt: new Date(),
metadataEditedByUserId: 1,
dataEditedAt: new Date(),
dataEditedByUserId: 1,
}
// dummy variable and its grapherConfigETL
const dummyVariable = {
id: variableId,
unit: "kg",
coverage: "Global by country",
timespan: "2000-2020",
datasetId: 1,
display: '{ "unit": "kg", "shortUnit": "kg" }',
}
const testVariableConfigETL = {
$schema: latestGrapherConfigSchema,
hasMapTab: true,
note: "Indicator note",
selectedEntityNames: ["France", "Italy", "Spain"],
hideRelativeToggle: false,
}
const testVariableConfigAdmin = {
$schema: latestGrapherConfigSchema,
title: "Admin title",
subtitle: "Admin subtitle",
}
// second dummy variable and its grapherConfigETL
const otherDummyVariable = {
...dummyVariable,
id: otherVariableId,
}
const otherTestVariableConfig = {
$schema: latestGrapherConfigSchema,
note: "Other indicator note",
}
const testChartConfig = {
$schema: latestGrapherConfigSchema,
slug: "test-chart",
title: "Test chart",
chartTypes: ["Marimekko"],
selectedEntityNames: [],
hideRelativeToggle: false,
dimensions: [
{
variableId,
property: "y",
},
],
}
const testMultiDimConfig = {
grapherConfigSchema: latestGrapherConfigSchema,
title: {
title: "Energy use",
titleVariant: "by energy source",
},
views: [
{
config: { title: "Total energy use" },
dimensions: {
source: "all",
metric: "total",
},
indicators: {
y: variableId,
},
},
{
dimensions: {
metric: "per_capita",
source: "all",
},
indicators: {
y: otherVariableId,
},
},
],
dimensions: [
{
name: "Energy source",
slug: "source",
choices: [
{
name: "All sources",
slug: "all",
group: "Aggregates",
description: "Total energy use",
},
],
},
{
name: "Metric",
slug: "metric",
choices: [
{
name: "Total consumption",
slug: "total",
description:
"The amount of energy consumed nationally per year",
},
{
name: "Consumption per capita",
slug: "per_capita",
description:
"The average amount of energy each person consumes per year",
},
],
},
],
}
beforeEach(async () => {
await testKnexInstance!(DatasetsTableName).insert([dummyDataset])
await testKnexInstance!(VariablesTableName).insert([
dummyVariable,
otherDummyVariable,
])
})
it("should be able to edit ETL grapher configs via the api", async () => {
// make sure the database is in a clean state
const chartConfigsCount = await getCountForTable(ChartConfigsTableName)
expect(chartConfigsCount).toBe(0)
// add a grapher config for a variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(testVariableConfigETL),
})
// get inserted configs from the database
const row = await testKnexInstance!(ChartConfigsTableName).first()
const patchConfigETL = JSON.parse(row.patch)
const fullConfigETL = JSON.parse(row.full)
// for ETL configs, patch and full configs should be the same
expect(patchConfigETL).toEqual(fullConfigETL)
// check that the dimensions field were added to the config
const processedTestVariableConfigETL = {
...testVariableConfigETL,
// automatically added
dimensions: [
{
property: "y",
variableId,
},
],
}
expect(patchConfigETL).toEqual(processedTestVariableConfigETL)
// fetch the admin+etl merged grapher config
let mergedGrapherConfig = await fetchJsonFromAdminApi(
`/variables/mergedGrapherConfig/${variableId}.json`
)
// since no admin-authored config exists, the merged config should be
// the same as the ETL config
expect(mergedGrapherConfig).toEqual(fullConfigETL)
// add an admin-authored config for the variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigAdmin`,
body: JSON.stringify(testVariableConfigAdmin),
})
// fetch the merged grapher config and verify that the admin-authored
// config has been merged in
mergedGrapherConfig = await fetchJsonFromAdminApi(
`/variables/mergedGrapherConfig/${variableId}.json`
)
expect(mergedGrapherConfig).toEqual({
...processedTestVariableConfigETL,
...testVariableConfigAdmin,
})
// create mdim config that uses both of the variables
await makeRequestAgainstAdminApi({
method: "PUT",
path: "/multi-dim/energy",
body: JSON.stringify(testMultiDimConfig),
})
const mdim = await testKnexInstance!(MultiDimDataPagesTableName).first()
expect(mdim.slug).toBe("energy")
const savedMdimConfig = JSON.parse(mdim.config)
// variableId should be normalized to an array
expect(savedMdimConfig.views[0].indicators.y).toBeInstanceOf(Array)
const [mdxcc1, mdxcc2] = await testKnexInstance!(
MultiDimXChartConfigsTableName
)
expect(mdxcc1.multiDimId).toBe(mdim.id)
expect(mdxcc1.viewId).toBe("total__all")
expect(mdxcc1.variableId).toBe(variableId)
expect(mdxcc2.multiDimId).toBe(mdim.id)
expect(mdxcc2.viewId).toBe("per_capita__all")
expect(mdxcc2.variableId).toBe(otherVariableId)
// view config should override the variable config
const expectedMergedViewConfig = {
...mergedGrapherConfig,
title: "Total energy use",
selectedEntityNames: [], // mdims define their own default entities
slug: "energy",
}
const fullViewConfig1 = await testKnexInstance!(ChartConfigsTableName)
.where("id", mdxcc1.chartConfigId)
.first()
expect(JSON.parse(fullViewConfig1.full)).toEqual(
expectedMergedViewConfig
)
// update the admin-authored config for the variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigAdmin`,
body: JSON.stringify({
...testVariableConfigAdmin,
subtitle: "Newly updated subtitle",
}),
})
const expectedMergedViewConfigUpdated = {
...expectedMergedViewConfig,
subtitle: "Newly updated subtitle",
}
const fullViewConfig1Updated = await testKnexInstance!(
ChartConfigsTableName
)
.where("id", mdxcc1.chartConfigId)
.first()
expect(JSON.parse(fullViewConfig1Updated.full)).toEqual(
expectedMergedViewConfigUpdated
)
// clean-up the mdim tables
await testKnexInstance!(MultiDimXChartConfigsTableName).truncate()
await testKnexInstance!(MultiDimDataPagesTableName).delete()
await testKnexInstance!(ChartConfigsTableName)
.whereIn("id", [mdxcc1.chartConfigId, mdxcc2.chartConfigId])
.delete()
// delete the admin-authored grapher config we just added
// and verify that the merged config is now the same as the ETL config
await makeRequestAgainstAdminApi({
method: "DELETE",
path: `/variables/${variableId}/grapherConfigAdmin`,
})
mergedGrapherConfig = await fetchJsonFromAdminApi(
`/variables/mergedGrapherConfig/${variableId}.json`
)
expect(mergedGrapherConfig).toEqual(fullConfigETL)
// delete the ETL-authored grapher config we just added
await makeRequestAgainstAdminApi({
method: "DELETE",
path: `/variables/${variableId}/grapherConfigETL`,
})
// check that the row in the chart_configs table has been deleted
const chartConfigsCountAfterDelete = await getCountForTable(
ChartConfigsTableName
)
expect(chartConfigsCountAfterDelete).toBe(0)
})
it("should update all charts that inherit from an indicator", async () => {
// make sure the database is in a clean state
const chartConfigsCount = await getCountForTable(ChartConfigsTableName)
expect(chartConfigsCount).toBe(0)
// add grapherConfigETL for the variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(testVariableConfigETL),
})
// add grapherConfigAdmin for the variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigAdmin`,
body: JSON.stringify(testVariableConfigAdmin),
})
// make a request to create a chart that inherits from the variable
const response = await makeRequestAgainstAdminApi({
method: "POST",
path: "/charts",
body: JSON.stringify(testChartConfig),
})
const chartId = response.chartId
// fetch the parent config of the chart and verify that it's the merged etl+admin config
const parentConfig = (
await fetchJsonFromAdminApi(`/charts/${chartId}.parent.json`)
)?.config
const mergedGrapherConfig = await fetchJsonFromAdminApi(
`/variables/mergedGrapherConfig/${variableId}.json`
)
expect(parentConfig).toEqual(mergedGrapherConfig)
// fetch the full config of the chart and verify that it's been merged
// with the indicator config
const fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfig).toEqual({
$schema: latestGrapherConfigSchema,
id: chartId,
isPublished: false,
version: 1,
slug: "test-chart",
title: "Test chart",
chartTypes: ["Marimekko"],
selectedEntityNames: [],
hideRelativeToggle: false,
dimensions: [{ variableId, property: "y" }],
subtitle: "Admin subtitle", // inherited from variable
note: "Indicator note", // inherited from variable
hasMapTab: true, // inherited from variable
})
// fetch the patch config and verify it's diffed correctly
const patchConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.patchConfig.json`
)
expect(patchConfig).toEqual({
$schema: latestGrapherConfigSchema,
id: chartId,
version: 1,
isPublished: false,
slug: "test-chart",
title: "Test chart",
chartTypes: ["Marimekko"],
selectedEntityNames: [],
dimensions: [{ variableId, property: "y" }],
// note that `hideRelativeToggle` is not included
})
// delete the ETL config
await makeRequestAgainstAdminApi({
method: "DELETE",
path: `/variables/${variableId}/grapherConfigETL`,
})
// delete the admin config
await makeRequestAgainstAdminApi({
method: "DELETE",
path: `/variables/${variableId}/grapherConfigAdmin`,
})
// fetch the parent config of the chart and verify there is none
const parentConfigAfterDelete = (
await fetchJsonFromAdminApi(`/charts/${chartId}.parent.json`)
)?.config
expect(parentConfigAfterDelete).toBeUndefined()
// fetch the full config of the chart and verify that it doesn't have
// values from the deleted ETL config
const fullConfigAfterDelete = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfigAfterDelete).toEqual({
$schema: latestGrapherConfigSchema,
id: chartId,
version: 1,
isPublished: false,
dimensions: [{ property: "y", variableId: 1 }],
selectedEntityNames: [],
slug: "test-chart",
title: "Test chart",
chartTypes: ["Marimekko"],
})
// fetch the patch config and verify it's diffed correctly
const patchConfigAfterDelete = await fetchJsonFromAdminApi(
`/charts/${chartId}.patchConfig.json`
)
expect(patchConfigAfterDelete).toEqual({
$schema: latestGrapherConfigSchema,
id: chartId,
version: 1,
isPublished: false,
slug: "test-chart",
title: "Test chart",
chartTypes: ["Marimekko"],
selectedEntityNames: [],
dimensions: [
{
variableId,
property: "y",
},
],
// note that hideRelativeToggle is not included
})
})
it("should update chart configs when inheritance is enabled/disabled", async () => {
const checkInheritance = async ({
shouldBeEnabled,
}: {
shouldBeEnabled?: boolean
}): Promise<void> => {
const chartRow = await testKnexInstance!(ChartsTableName)
.where({ id: chartId })
.first()
const fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
if (shouldBeEnabled) {
expect(chartRow.isInheritanceEnabled).toBeTruthy()
expect(fullConfig).toHaveProperty("note", "Indicator note")
expect(fullConfig).toHaveProperty("hasMapTab", true)
} else {
expect(chartRow.isInheritanceEnabled).toBeFalsy()
expect(fullConfig).not.toHaveProperty("note")
expect(fullConfig).not.toHaveProperty("hasMapTab")
}
}
// make sure the database is in a clean state
const chartConfigsCount = await getCountForTable(ChartConfigsTableName)
expect(chartConfigsCount).toBe(0)
// add grapherConfigETL for the variable
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(testVariableConfigETL),
})
// create a chart whose parent is the given indicator
const response = await makeRequestAgainstAdminApi({
method: "POST",
path: "/charts",
body: JSON.stringify(testChartConfig),
})
const chartId = response.chartId
// get the ETL config from the database
const row = await testKnexInstance!(ChartConfigsTableName).first()
const fullConfigETL = JSON.parse(row.full)
// check the parent of the chart
const parent = await fetchJsonFromAdminApi(
`/charts/${chartId}.parent.json`
)
expect(parent.variableId).toEqual(variableId)
expect(parent.config).toEqual(fullConfigETL)
// verify that inheritance is enabled by default
await checkInheritance({ shouldBeEnabled: true })
// disable inheritance
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}?inheritance=disable`,
body: JSON.stringify(testChartConfig),
})
await checkInheritance({ shouldBeEnabled: false })
// enable inheritance
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}?inheritance=enable`,
body: JSON.stringify(testChartConfig),
})
await checkInheritance({ shouldBeEnabled: true })
// update the config without making changes to the inheritance setting
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}`,
body: JSON.stringify(testChartConfig),
})
await checkInheritance({ shouldBeEnabled: true })
})
it("should recompute configs when the parent of a chart changes", async () => {
// add grapherConfigETL for the variables
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(testVariableConfigETL),
})
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/variables/${otherVariableId}/grapherConfigETL`,
body: JSON.stringify(otherTestVariableConfig),
})
// create a chart whose parent is the first indicator
const response = await makeRequestAgainstAdminApi({
method: "POST",
path: "/charts?inheritance=enable",
body: JSON.stringify(testChartConfig),
})
const chartId = response.chartId
// check that chart inherits from the first indicator
let fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfig).toHaveProperty("note", "Indicator note")
// update chart config so that it now inherits from the second indicator
const chartConfigWithOtherIndicatorAsParent = {
...testChartConfig,
dimensions: [
{
variableId: otherVariableId,
property: "y",
},
],
}
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}`,
body: JSON.stringify(chartConfigWithOtherIndicatorAsParent),
})
// check that chart inherits from the second indicator
fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfig).toHaveProperty("note", "Other indicator note")
// update chart config so that it doesn't inherit from an indicator
const chartConfigWithoutDimensions = omitUndefinedValues({
...testChartConfig,
dimensions: undefined,
})
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}`,
body: JSON.stringify(chartConfigWithoutDimensions),
})
// check that chart doesn't inherit from any indicator
fullConfig = await fetchJsonFromAdminApi(
`/charts/${chartId}.config.json`
)
expect(fullConfig).not.toHaveProperty("note")
})
it("should update timestamps on chart update", async () => {
// make sure the database is in a clean state
const chartCount = await getCountForTable(ChartsTableName)
expect(chartCount).toBe(0)
const chartConfigsCount = await getCountForTable(ChartConfigsTableName)
expect(chartConfigsCount).toBe(0)
// make a request to create a chart
const response = await makeRequestAgainstAdminApi({
method: "POST",
path: "/charts",
body: JSON.stringify(testChartConfig),
})
const chartId = response.chartId
// helper functions to get the updatedAt timestamp of the chart and its config
const chartUpdatedAt = async (): Promise<Date> =>
(await testKnexInstance!(ChartsTableName).first()).updatedAt
const configUpdatedAt = async (): Promise<Date> =>
(await testKnexInstance!(ChartConfigsTableName).first()).updatedAt
// verify that both updatedAt timestamps are null initially
expect(await chartUpdatedAt()).toBeNull()
expect(await configUpdatedAt()).toBeNull()
// update the chart
await makeRequestAgainstAdminApi({
method: "PUT",
path: `/charts/${chartId}`,
body: JSON.stringify({ ...testChartConfig, title: "New title" }),
})
// verify that the updatedAt timestamps are the same
const chartAfterUpdate = await chartUpdatedAt()
const configAfterUpdate = await configUpdatedAt()
expect(chartAfterUpdate).not.toBeNull()
expect(configAfterUpdate).not.toBeNull()
expect(chartAfterUpdate).toEqual(configAfterUpdate)
})
it("should return an error if the schema is missing", async () => {
const invalidConfig = {
title: "Title",
// note that the $schema field is missing
}
const json = await makeRequestAgainstAdminApi(
{
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(invalidConfig),
},
{ verifySuccess: false }
)
expect(json.success).toBe(false)
})
it("should return an error if the schema is invalid", async () => {
const invalidConfig = {
$schema: "invalid", // note that the $schema field is invalid
title: "Title",
}
const json = await makeRequestAgainstAdminApi(
{
method: "PUT",
path: `/variables/${variableId}/grapherConfigETL`,
body: JSON.stringify(invalidConfig),
},
{ verifySuccess: false }
)
expect(json.success).toBe(false)
})
})
describe("OwidAdminApp: tag graph", () => {
// prettier-ignore
const dummyTags: DbInsertTag[] = [
{ name: TagGraphRootName, id: 1 },
{ name: "Energy and Environment", id: 2 },
{ name: "Energy", slug: "energy", id: 3 },
{ name: "Nuclear Energy", slug: "nuclear-energy", id: 4 },
{ name: "CO2 & Greenhouse Gas Emissions", slug: "co2-and-greenhouse-gas-emissions", id: 5 },
]
const dummyTagGraph: DbInsertTagGraphNode[] = [
{ parentId: 1, childId: 2 },
{ parentId: 2, childId: 3, weight: 110 },
{ parentId: 2, childId: 5 },
{ parentId: 3, childId: 4 },
{ parentId: 5, childId: 4 },
]
function makeDummyTopicPage(slug: string): DbInsertPostGdoc {
return {
slug,
content: JSON.stringify({
type: OwidGdocType.TopicPage,
authors: [] as string[],
}),
id: slug,
published: 1,
createdAt: new Date(),
publishedAt: new Date(),
markdown: "",
}
}
const dummyTopicPages: DbInsertPostGdoc[] = [
makeDummyTopicPage("energy"),
makeDummyTopicPage("nuclear-energy"),
makeDummyTopicPage("co2-and-greenhouse-gas-emissions"),
]
const dummyPostTags: DbInsertPostGdocXTag[] = [
{ gdocId: "energy", tagId: 3 },
{ gdocId: "nuclear-energy", tagId: 4 },
{ gdocId: "co2-and-greenhouse-gas-emissions", tagId: 5 },
]
beforeEach(async () => {
await testKnexInstance!(TagsTableName).insert(dummyTags)
await testKnexInstance!(TagGraphTableName).insert(dummyTagGraph)
await testKnexInstance!(PostsGdocsTableName).insert(dummyTopicPages)
await testKnexInstance!(PostsGdocsXTagsTableName).insert(dummyPostTags)
})
it("should be able to see all the tags", async () => {
const tags = await fetchJsonFromAdminApi("/tags.json")
expect(tags).toEqual({
tags: [
{
id: 5,
isTopic: 1,
name: "CO2 & Greenhouse Gas Emissions",
slug: "co2-and-greenhouse-gas-emissions",
},
{
id: 3,
isTopic: 1,
name: "Energy",