summaryrefslogtreecommitdiffstats
path: root/utils/config_test.go
blob: a08b73632c0718925a4edb4e04a68465878b00aa (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
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See License.txt for license information.

package utils

import (
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/mattermost/mattermost-server/model"
)

func TestConfig(t *testing.T) {
	TranslationsPreInit()
	_, _, _, err := LoadConfig("config.json")
	require.Nil(t, err)
}

func TestReadConfig(t *testing.T) {
	TranslationsPreInit()

	_, _, err := ReadConfig(bytes.NewReader([]byte(``)), false)
	require.EqualError(t, err, "parsing error at line 1, character 1: unexpected end of JSON input")

	_, _, err = ReadConfig(bytes.NewReader([]byte(`
		{
			malformed
	`)), false)
	require.EqualError(t, err, "parsing error at line 3, character 5: invalid character 'm' looking for beginning of object key string")
}

func TestReadConfig_PluginSettings(t *testing.T) {
	TranslationsPreInit()

	config, _, err := ReadConfig(bytes.NewReader([]byte(`{
		"PluginSettings": {
			"Directory": "/temp/mattermost-plugins",
			"Plugins": {
				"com.example.plugin": {
					"number": 1,
					"string": "abc",
					"boolean": false,
					"abc.def.ghi": {
						"abc": 123,
						"def": "456"
					}
				}
			},
			"PluginStates": {
				"com.example.plugin": {
					"enable": true
				}
			}
		}
	}`)), false)
	require.Nil(t, err)

	assert.Equal(t, "/temp/mattermost-plugins", *config.PluginSettings.Directory)
	assert.Contains(t, config.PluginSettings.Plugins, "com.example.plugin")
	assert.Equal(t, map[string]interface{}{
		"number":  float64(1),
		"string":  "abc",
		"boolean": false,
		"abc.def.ghi": map[string]interface{}{
			"abc": float64(123),
			"def": "456",
		},
	}, config.PluginSettings.Plugins["com.example.plugin"])
	assert.Contains(t, config.PluginSettings.PluginStates, "com.example.plugin")
	assert.Equal(t, model.PluginState{
		Enable: true,
	}, *config.PluginSettings.PluginStates["com.example.plugin"])
}

func TestTimezoneConfig(t *testing.T) {
	TranslationsPreInit()
	supportedTimezones := LoadTimezones("timezones.json")
	assert.Equal(t, len(supportedTimezones) > 0, true)

	supportedTimezones2 := LoadTimezones("timezones_file_does_not_exists.json")
	assert.Equal(t, len(supportedTimezones2) > 0, true)
}

func TestFindConfigFile(t *testing.T) {
	t.Run("config.json in current working directory, not inside config/", func(t *testing.T) {
		// Force a unique working directory
		cwd, err := ioutil.TempDir("", "")
		require.NoError(t, err)
		defer os.RemoveAll(cwd)

		prevDir, err := os.Getwd()
		require.NoError(t, err)
		defer os.Chdir(prevDir)
		os.Chdir(cwd)

		configJson, err := filepath.Abs("config.json")
		require.NoError(t, err)
		require.NoError(t, ioutil.WriteFile(configJson, []byte("{}"), 0600))

		// Relative paths end up getting symlinks fully resolved.
		configJsonResolved, err := filepath.EvalSymlinks(configJson)
		require.NoError(t, err)

		assert.Equal(t, configJsonResolved, FindConfigFile("config.json"))
	})

	t.Run("config/config.json from various paths", func(t *testing.T) {
		// Create the following directory structure:
		// tmpDir1/
		//   config/
		//     config.json
		//   tmpDir2/
		//     tmpDir3/
		//       tmpDir4/
		//         tmpDir5/
		tmpDir1, err := ioutil.TempDir("", "")
		require.NoError(t, err)
		defer os.RemoveAll(tmpDir1)

		err = os.Mkdir(filepath.Join(tmpDir1, "config"), 0700)
		require.NoError(t, err)

		tmpDir2, err := ioutil.TempDir(tmpDir1, "")
		require.NoError(t, err)

		tmpDir3, err := ioutil.TempDir(tmpDir2, "")
		require.NoError(t, err)

		tmpDir4, err := ioutil.TempDir(tmpDir3, "")
		require.NoError(t, err)

		tmpDir5, err := ioutil.TempDir(tmpDir4, "")
		require.NoError(t, err)

		configJson := filepath.Join(tmpDir1, "config", "config.json")
		require.NoError(t, ioutil.WriteFile(configJson, []byte("{}"), 0600))

		// Relative paths end up getting symlinks fully resolved, so use this below as necessary.
		configJsonResolved, err := filepath.EvalSymlinks(configJson)
		require.NoError(t, err)

		testCases := []struct {
			Description string
			Cwd         *string
			FileName    string
			Expected    string
		}{
			{
				"absolute path to config.json",
				nil,
				configJson,
				configJson,
			},
			{
				"absolute path to config.json from directory containing config.json",
				&tmpDir1,
				configJson,
				configJson,
			},
			{
				"relative path to config.json from directory containing config.json",
				&tmpDir1,
				"config.json",
				configJsonResolved,
			},
			{
				"subdirectory of directory containing config.json",
				&tmpDir2,
				"config.json",
				configJsonResolved,
			},
			{
				"twice-nested subdirectory of directory containing config.json",
				&tmpDir3,
				"config.json",
				configJsonResolved,
			},
			{
				"thrice-nested subdirectory of directory containing config.json",
				&tmpDir4,
				"config.json",
				configJsonResolved,
			},
			{
				"can't find from four nesting levels deep",
				&tmpDir5,
				"config.json",
				"",
			},
		}

		for _, testCase := range testCases {
			t.Run(testCase.Description, func(t *testing.T) {
				if testCase.Cwd != nil {
					prevDir, err := os.Getwd()
					require.NoError(t, err)
					defer os.Chdir(prevDir)
					os.Chdir(*testCase.Cwd)
				}

				assert.Equal(t, testCase.Expected, FindConfigFile(testCase.FileName))
			})
		}
	})

	t.Run("config/config.json relative to executable", func(t *testing.T) {
		osExecutable, err := os.Executable()
		require.NoError(t, err)
		osExecutableDir := filepath.Dir(osExecutable)

		// Force a working directory different than the executable.
		cwd, err := ioutil.TempDir("", "")
		require.NoError(t, err)
		defer os.RemoveAll(cwd)

		prevDir, err := os.Getwd()
		require.NoError(t, err)
		defer os.Chdir(prevDir)
		os.Chdir(cwd)

		testCases := []struct {
			Description  string
			RelativePath string
		}{
			{
				"config/config.json",
				".",
			},
			{
				"../config/config.json",
				"../",
			},
		}

		for _, testCase := range testCases {
			t.Run(testCase.Description, func(t *testing.T) {
				// Install the config in config/config.json relative to the executable
				configJson := filepath.Join(osExecutableDir, testCase.RelativePath, "config", "config.json")
				require.NoError(t, os.Mkdir(filepath.Dir(configJson), 0700))
				require.NoError(t, ioutil.WriteFile(configJson, []byte("{}"), 0600))
				defer os.RemoveAll(filepath.Dir(configJson))

				// Relative paths end up getting symlinks fully resolved.
				configJsonResolved, err := filepath.EvalSymlinks(configJson)
				require.NoError(t, err)

				assert.Equal(t, configJsonResolved, FindConfigFile("config.json"))
			})
		}
	})
}

func TestFindFile(t *testing.T) {
	t.Run("files from various paths", func(t *testing.T) {
		// Create the following directory structure:
		// tmpDir1/
		//   file1.json
		//   file2.xml
		//   other.txt
		//   tmpDir2/
		//     other.txt/ [directory]
		//     tmpDir3/
		//       tmpDir4/
		//         tmpDir5/
		tmpDir1, err := ioutil.TempDir("", "")
		require.NoError(t, err)
		defer os.RemoveAll(tmpDir1)

		tmpDir2, err := ioutil.TempDir(tmpDir1, "")
		require.NoError(t, err)

		err = os.Mkdir(filepath.Join(tmpDir2, "other.txt"), 0700)
		require.NoError(t, err)

		tmpDir3, err := ioutil.TempDir(tmpDir2, "")
		require.NoError(t, err)

		tmpDir4, err := ioutil.TempDir(tmpDir3, "")
		require.NoError(t, err)

		tmpDir5, err := ioutil.TempDir(tmpDir4, "")
		require.NoError(t, err)

		type testCase struct {
			Description string
			Cwd         *string
			FileName    string
			Expected    string
		}

		testCases := []testCase{}

		for _, fileName := range []string{"file1.json", "file2.xml", "other.txt"} {
			filePath := filepath.Join(tmpDir1, fileName)
			require.NoError(t, ioutil.WriteFile(filePath, []byte("{}"), 0600))

			// Relative paths end up getting symlinks fully resolved, so use this below as necessary.
			filePathResolved, err := filepath.EvalSymlinks(filePath)
			require.NoError(t, err)

			testCases = append(testCases, []testCase{
				{
					fmt.Sprintf("absolute path to %s", fileName),
					nil,
					filePath,
					filePath,
				},
				{
					fmt.Sprintf("absolute path to %s from containing directory", fileName),
					&tmpDir1,
					filePath,
					filePath,
				},
				{
					fmt.Sprintf("relative path to %s from containing directory", fileName),
					&tmpDir1,
					fileName,
					filePathResolved,
				},
				{
					fmt.Sprintf("%s: subdirectory of containing directory", fileName),
					&tmpDir2,
					fileName,
					filePathResolved,
				},
				{
					fmt.Sprintf("%s: twice-nested subdirectory of containing directory", fileName),
					&tmpDir3,
					fileName,
					filePathResolved,
				},
				{
					fmt.Sprintf("%s: thrice-nested subdirectory of containing directory", fileName),
					&tmpDir4,
					fileName,
					filePathResolved,
				},
				{
					fmt.Sprintf("%s: can't find from four nesting levels deep", fileName),
					&tmpDir5,
					fileName,
					"",
				},
			}...)
		}

		for _, testCase := range testCases {
			t.Run(testCase.Description, func(t *testing.T) {
				if testCase.Cwd != nil {
					prevDir, err := os.Getwd()
					require.NoError(t, err)
					defer os.Chdir(prevDir)
					os.Chdir(*testCase.Cwd)
				}

				assert.Equal(t, testCase.Expected, FindFile(testCase.FileName))
			})
		}
	})
}

func TestConfigFromEnviroVars(t *testing.T) {
	TranslationsPreInit()

	config := `{
		"ServiceSettings": {
			"EnableCommands": true,
			"ReadTimeout": 100
		},
		"TeamSettings": {
			"SiteName": "Mattermost",
			"CustomBrandText": ""
		},
		"SupportSettings": {
			"TermsOfServiceLink": "https://about.mattermost.com/default-terms/"
		}
	}`

	t.Run("string settings", func(t *testing.T) {
		os.Setenv("MM_TEAMSETTINGS_SITENAME", "From Environment")
		os.Setenv("MM_TEAMSETTINGS_CUSTOMBRANDTEXT", "Custom Brand")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if cfg.TeamSettings.SiteName != "From Environment" {
			t.Fatal("Couldn't read config from environment var")
		}

		if *cfg.TeamSettings.CustomBrandText != "Custom Brand" {
			t.Fatal("Couldn't read config from environment var")
		}

		if teamSettings, ok := envCfg["TeamSettings"]; !ok {
			t.Fatal("TeamSettings is missing from envConfig")
		} else if teamSettingsAsMap, ok := teamSettings.(map[string]interface{}); !ok {
			t.Fatal("TeamSettings is not a map in envConfig")
		} else {
			if siteNameInEnv, ok := teamSettingsAsMap["SiteName"].(bool); !ok || !siteNameInEnv {
				t.Fatal("SiteName should be in envConfig")
			}

			if customBrandTextInEnv, ok := teamSettingsAsMap["CustomBrandText"].(bool); !ok || !customBrandTextInEnv {
				t.Fatal("SiteName should be in envConfig")
			}
		}

		os.Unsetenv("MM_TEAMSETTINGS_SITENAME")
		os.Unsetenv("MM_TEAMSETTINGS_CUSTOMBRANDTEXT")

		cfg, envCfg, err = ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if cfg.TeamSettings.SiteName != "Mattermost" {
			t.Fatal("should have been reset")
		}

		if _, ok := envCfg["TeamSettings"]; ok {
			t.Fatal("TeamSettings should be missing from envConfig")
		}
	})

	t.Run("boolean setting", func(t *testing.T) {
		os.Setenv("MM_SERVICESETTINGS_ENABLECOMMANDS", "false")
		defer os.Unsetenv("MM_SERVICESETTINGS_ENABLECOMMANDS")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if *cfg.ServiceSettings.EnableCommands {
			t.Fatal("Couldn't read config from environment var")
		}

		if serviceSettings, ok := envCfg["ServiceSettings"]; !ok {
			t.Fatal("ServiceSettings is missing from envConfig")
		} else if serviceSettingsAsMap, ok := serviceSettings.(map[string]interface{}); !ok {
			t.Fatal("ServiceSettings is not a map in envConfig")
		} else {
			if enableCommandsInEnv, ok := serviceSettingsAsMap["EnableCommands"].(bool); !ok || !enableCommandsInEnv {
				t.Fatal("EnableCommands should be in envConfig")
			}
		}
	})

	t.Run("integer setting", func(t *testing.T) {
		os.Setenv("MM_SERVICESETTINGS_READTIMEOUT", "400")
		defer os.Unsetenv("MM_SERVICESETTINGS_READTIMEOUT")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if *cfg.ServiceSettings.ReadTimeout != 400 {
			t.Fatal("Couldn't read config from environment var")
		}

		if serviceSettings, ok := envCfg["ServiceSettings"]; !ok {
			t.Fatal("ServiceSettings is missing from envConfig")
		} else if serviceSettingsAsMap, ok := serviceSettings.(map[string]interface{}); !ok {
			t.Fatal("ServiceSettings is not a map in envConfig")
		} else {
			if readTimeoutInEnv, ok := serviceSettingsAsMap["ReadTimeout"].(bool); !ok || !readTimeoutInEnv {
				t.Fatal("ReadTimeout should be in envConfig")
			}
		}
	})

	t.Run("setting missing from config.json", func(t *testing.T) {
		os.Setenv("MM_SERVICESETTINGS_SITEURL", "https://example.com")
		defer os.Unsetenv("MM_SERVICESETTINGS_SITEURL")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if *cfg.ServiceSettings.SiteURL != "https://example.com" {
			t.Fatal("Couldn't read config from environment var")
		}

		if serviceSettings, ok := envCfg["ServiceSettings"]; !ok {
			t.Fatal("ServiceSettings is missing from envConfig")
		} else if serviceSettingsAsMap, ok := serviceSettings.(map[string]interface{}); !ok {
			t.Fatal("ServiceSettings is not a map in envConfig")
		} else {
			if siteURLInEnv, ok := serviceSettingsAsMap["SiteURL"].(bool); !ok || !siteURLInEnv {
				t.Fatal("SiteURL should be in envConfig")
			}
		}
	})

	t.Run("empty string setting", func(t *testing.T) {
		os.Setenv("MM_SUPPORTSETTINGS_TERMSOFSERVICELINK", "")
		defer os.Unsetenv("MM_SUPPORTSETTINGS_TERMSOFSERVICELINK")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if *cfg.SupportSettings.TermsOfServiceLink != "" {
			t.Fatal("Couldn't read empty TermsOfServiceLink from environment var")
		}

		if supportSettings, ok := envCfg["SupportSettings"]; !ok {
			t.Fatal("SupportSettings is missing from envConfig")
		} else if supportSettingsAsMap, ok := supportSettings.(map[string]interface{}); !ok {
			t.Fatal("SupportSettings is not a map in envConfig")
		} else {
			if termsOfServiceLinkInEnv, ok := supportSettingsAsMap["TermsOfServiceLink"].(bool); !ok || !termsOfServiceLinkInEnv {
				t.Fatal("TermsOfServiceLink should be in envConfig")
			}
		}
	})

	t.Run("plugin directory settings", func(t *testing.T) {
		os.Setenv("MM_PLUGINSETTINGS_DIRECTORY", "/temp/plugins")
		os.Setenv("MM_PLUGINSETTINGS_CLIENTDIRECTORY", "/temp/clientplugins")
		defer os.Unsetenv("MM_PLUGINSETTINGS_DIRECTORY")
		defer os.Unsetenv("MM_PLUGINSETTINGS_CLIENTDIRECTORY")

		cfg, envCfg, err := ReadConfig(strings.NewReader(config), true)
		require.Nil(t, err)

		if *cfg.PluginSettings.Directory != "/temp/plugins" {
			t.Fatal("Couldn't read Directory from environment var")
		}
		if *cfg.PluginSettings.ClientDirectory != "/temp/clientplugins" {
			t.Fatal("Couldn't read ClientDirectory from environment var")
		}

		if pluginSettings, ok := envCfg["PluginSettings"]; !ok {
			t.Fatal("PluginSettings is missing from envConfig")
		} else if pluginSettingsAsMap, ok := pluginSettings.(map[string]interface{}); !ok {
			t.Fatal("PluginSettings is not a map in envConfig")
		} else {
			if directory, ok := pluginSettingsAsMap["Directory"].(bool); !ok || !directory {
				t.Fatal("Directory should be in envConfig")
			}
			if clientDirectory, ok := pluginSettingsAsMap["ClientDirectory"].(bool); !ok || !clientDirectory {
				t.Fatal("ClientDirectory should be in envConfig")
			}
		}
	})
}

func TestValidateLocales(t *testing.T) {
	TranslationsPreInit()
	cfg, _, _, err := LoadConfig("config.json")
	require.Nil(t, err)

	*cfg.LocalizationSettings.DefaultServerLocale = "en"
	*cfg.LocalizationSettings.DefaultClientLocale = "en"
	*cfg.LocalizationSettings.AvailableLocales = ""

	// t.Logf("*cfg.LocalizationSettings.DefaultClientLocale: %+v", *cfg.LocalizationSettings.DefaultClientLocale)
	if err := ValidateLocales(cfg); err != nil {
		t.Fatal("Should have not returned an error")
	}

	// validate DefaultServerLocale
	*cfg.LocalizationSettings.DefaultServerLocale = "junk"
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.DefaultServerLocale != "en" {
			t.Fatal("DefaultServerLocale should have assigned to en as a default value")
		}
	} else {
		t.Fatal("Should have returned an error validating DefaultServerLocale")
	}

	*cfg.LocalizationSettings.DefaultServerLocale = ""
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.DefaultServerLocale != "en" {
			t.Fatal("DefaultServerLocale should have assigned to en as a default value")
		}
	} else {
		t.Fatal("Should have returned an error validating DefaultServerLocale")
	}

	*cfg.LocalizationSettings.AvailableLocales = "en"
	*cfg.LocalizationSettings.DefaultServerLocale = "de"
	if err := ValidateLocales(cfg); err != nil {
		if strings.Contains(*cfg.LocalizationSettings.AvailableLocales, *cfg.LocalizationSettings.DefaultServerLocale) {
			t.Fatal("DefaultServerLocale should not be added to AvailableLocales")
		}
		t.Fatal("Should have not returned an error validating DefaultServerLocale")
	}

	// validate DefaultClientLocale
	*cfg.LocalizationSettings.AvailableLocales = ""
	*cfg.LocalizationSettings.DefaultClientLocale = "junk"
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.DefaultClientLocale != "en" {
			t.Fatal("DefaultClientLocale should have assigned to en as a default value")
		}
	} else {

		t.Fatal("Should have returned an error validating DefaultClientLocale")
	}

	*cfg.LocalizationSettings.DefaultClientLocale = ""
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.DefaultClientLocale != "en" {
			t.Fatal("DefaultClientLocale should have assigned to en as a default value")
		}
	} else {
		t.Fatal("Should have returned an error validating DefaultClientLocale")
	}

	*cfg.LocalizationSettings.AvailableLocales = "en"
	*cfg.LocalizationSettings.DefaultClientLocale = "de"
	if err := ValidateLocales(cfg); err != nil {
		if !strings.Contains(*cfg.LocalizationSettings.AvailableLocales, *cfg.LocalizationSettings.DefaultClientLocale) {
			t.Fatal("DefaultClientLocale should have added to AvailableLocales")
		}
	} else {
		t.Fatal("Should have returned an error validating DefaultClientLocale")
	}

	// validate AvailableLocales
	*cfg.LocalizationSettings.DefaultServerLocale = "en"
	*cfg.LocalizationSettings.DefaultClientLocale = "en"
	*cfg.LocalizationSettings.AvailableLocales = "junk"
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.AvailableLocales != "" {
			t.Fatal("AvailableLocales should have assigned to empty string as a default value")
		}
	} else {
		t.Fatal("Should have returned an error validating AvailableLocales")
	}

	*cfg.LocalizationSettings.AvailableLocales = "en,de,junk"
	if err := ValidateLocales(cfg); err != nil {
		if *cfg.LocalizationSettings.AvailableLocales != "" {
			t.Fatal("AvailableLocales should have assigned to empty string as a default value")
		}
	} else {
		t.Fatal("Should have returned an error validating AvailableLocales")
	}

	*cfg.LocalizationSettings.DefaultServerLocale = "fr"
	*cfg.LocalizationSettings.DefaultClientLocale = "de"
	*cfg.LocalizationSettings.AvailableLocales = "en"
	if err := ValidateLocales(cfg); err != nil {
		if strings.Contains(*cfg.LocalizationSettings.AvailableLocales, *cfg.LocalizationSettings.DefaultServerLocale) {
			t.Fatal("DefaultServerLocale should not be added to AvailableLocales")
		}
		if !strings.Contains(*cfg.LocalizationSettings.AvailableLocales, *cfg.LocalizationSettings.DefaultClientLocale) {
			t.Fatal("DefaultClientLocale should have added to AvailableLocales")
		}
	} else {
		t.Fatal("Should have returned an error validating AvailableLocales")
	}
}

func TestGetClientConfig(t *testing.T) {
	t.Parallel()
	testCases := []struct {
		description    string
		config         *model.Config
		diagnosticId   string
		license        *model.License
		expectedFields map[string]string
	}{
		{
			"unlicensed",
			&model.Config{
				EmailSettings: model.EmailSettings{
					EmailNotificationContentsType: sToP(model.EMAIL_NOTIFICATION_CONTENTS_FULL),
				},
				ThemeSettings: model.ThemeSettings{
					// Ignored, since not licensed.
					AllowCustomThemes: bToP(false),
				},
			},
			"",
			nil,
			map[string]string{
				"DiagnosticId":                  "",
				"EmailNotificationContentsType": "full",
				"AllowCustomThemes":             "true",
			},
		},
		{
			"licensed, but not for theme management",
			&model.Config{
				EmailSettings: model.EmailSettings{
					EmailNotificationContentsType: sToP(model.EMAIL_NOTIFICATION_CONTENTS_FULL),
				},
				ThemeSettings: model.ThemeSettings{
					// Ignored, since not licensed.
					AllowCustomThemes: bToP(false),
				},
			},
			"tag1",
			&model.License{
				Features: &model.Features{
					ThemeManagement: bToP(false),
				},
			},
			map[string]string{
				"DiagnosticId":                  "tag1",
				"EmailNotificationContentsType": "full",
				"AllowCustomThemes":             "true",
			},
		},
		{
			"licensed for theme management",
			&model.Config{
				EmailSettings: model.EmailSettings{
					EmailNotificationContentsType: sToP(model.EMAIL_NOTIFICATION_CONTENTS_FULL),
				},
				ThemeSettings: model.ThemeSettings{
					AllowCustomThemes: bToP(false),
				},
			},
			"tag2",
			&model.License{
				Features: &model.Features{
					ThemeManagement: bToP(true),
				},
			},
			map[string]string{
				"DiagnosticId":                  "tag2",
				"EmailNotificationContentsType": "full",
				"AllowCustomThemes":             "false",
			},
		},
	}

	for _, testCase := range testCases {
		testCase := testCase
		t.Run(testCase.description, func(t *testing.T) {
			t.Parallel()

			testCase.config.SetDefaults()
			if testCase.license != nil {
				testCase.license.Features.SetDefaults()
			}

			configMap := GenerateClientConfig(testCase.config, testCase.diagnosticId, testCase.license)
			for expectedField, expectedValue := range testCase.expectedFields {
				actualValue, ok := configMap[expectedField]
				assert.True(t, ok, fmt.Sprintf("config does not contain %v", expectedField))
				assert.Equal(t, expectedValue, actualValue)
			}
		})
	}
}

func sToP(s string) *string {
	return &s
}

func bToP(b bool) *bool {
	return &b
}

func TestGetDefaultsFromStruct(t *testing.T) {
	s := struct {
		TestSettings struct {
			IntValue    int
			BoolValue   bool
			StringValue string
		}
		PointerToTestSettings *struct {
			Value int
		}
	}{}

	defaults := getDefaultsFromStruct(s)

	assert.Equal(t, defaults["TestSettings.IntValue"], 0)
	assert.Equal(t, defaults["TestSettings.BoolValue"], false)
	assert.Equal(t, defaults["TestSettings.StringValue"], "")
	assert.Equal(t, defaults["PointerToTestSettings.Value"], 0)
	assert.NotContains(t, defaults, "PointerToTestSettings")
	assert.Len(t, defaults, 4)
}