aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/controllers/__tests__/initConfig.spec.ts
blob: e386a07f864b010f9d95bfcedcfaf37a3dc55ee6 (plain) (blame)
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
/*
 * Copyright (C)  2021-2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { jest } from '@jest/globals';
import { mocked } from 'jest-mock';
import ms from 'ms';

import type ConfigPersistenceService from '../../services/ConfigPersistenceService';
import { Config, config as configModel } from '../../stores/Config';
import type Disposer from '../../utils/Disposer';
import { silenceLogger } from '../../utils/log';
import initConfig from '../initConfig';

let config: Config;
const persistenceService: ConfigPersistenceService = {
  readConfig: jest.fn(),
  writeConfig: jest.fn(),
  watchConfig: jest.fn(),
};
const lessThanThrottleMs = ms('0.1s');
const throttleMs = ms('1s');

beforeAll(() => {
  jest.useFakeTimers();
  silenceLogger();
});

beforeEach(() => {
  config = configModel.create();
});

describe('when initializing', () => {
  describe('when there is no config file', () => {
    beforeEach(() => {
      mocked(persistenceService.readConfig).mockResolvedValueOnce({
        found: false,
      });
    });

    it('should create a new config file', async () => {
      await initConfig(config, persistenceService);
      expect(persistenceService.writeConfig).toBeCalledTimes(1);
    });

    it('should bail if there is an an error creating the config file', async () => {
      mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo'));
      await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
    });
  });

  describe('when there is a valid config file', () => {
    beforeEach(() => {
      mocked(persistenceService.readConfig).mockResolvedValueOnce({
        found: true,
        data: {
          themeSource: 'dark',
        },
      });
    });

    it('should read the existing config file is there is one', async () => {
      await initConfig(config, persistenceService);
      expect(persistenceService.writeConfig).not.toBeCalled();
      expect(config.themeSource).toBe('dark');
    });

    it('should bail if it cannot set up a watcher', async () => {
      mocked(persistenceService.watchConfig).mockImplementationOnce(() => {
        throw new Error('boo');
      });
      await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
    });
  });

  it('should not apply an invalid config file', async () => {
    mocked(persistenceService.readConfig).mockResolvedValueOnce({
      found: true,
      data: {
        themeSource: -1,
      },
    });
    await initConfig(config, persistenceService);
    expect(config.themeSource).not.toBe(-1);
  });

  it('should bail if it cannot determine whether there is a config file', async () => {
    mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo'));
    await expect(() => initConfig(config, persistenceService)).rejects.toBeInstanceOf(Error);
  });
});

describe('when it has loaded the config', () => {
  let sutDisposer: Disposer;
  const watcherDisposer: Disposer = jest.fn();
  let configChangedCallback: () => Promise<void>;

  beforeEach(async () => {
    mocked(persistenceService.readConfig).mockResolvedValueOnce({
      found: true,
      data: {},
    });
    mocked(persistenceService.watchConfig).mockReturnValueOnce(watcherDisposer);
    sutDisposer = await initConfig(config, persistenceService, throttleMs);
    [[configChangedCallback]] = mocked(persistenceService.watchConfig).mock.calls;
    jest.resetAllMocks();
  });

  it('should throttle saving changes to the config file', () => {
    mocked(persistenceService.writeConfig).mockResolvedValue(undefined);
    config.setThemeSource('dark');
    jest.advanceTimersByTime(lessThanThrottleMs);
    config.setThemeSource('light');
    jest.advanceTimersByTime(throttleMs);
    expect(persistenceService.writeConfig).toBeCalledTimes(1);
  });

  it('should handle config writing errors gracefully', () => {
    mocked(persistenceService.writeConfig).mockRejectedValue(new Error('boo'));
    config.setThemeSource('dark');
    jest.advanceTimersByTime(throttleMs);
    expect(persistenceService.writeConfig).toBeCalledTimes(1);
  });

  it('should read the config file when it has changed', async () => {
    mocked(persistenceService.readConfig).mockResolvedValueOnce({
      found: true,
      data: {
        themeSource: 'dark',
      },
    });
    await configChangedCallback();
    // Do not write back the changes we have just read.
    expect(persistenceService.writeConfig).not.toBeCalled();
    expect(config.themeSource).toBe('dark');
  });

  it('should not apply an invalid config file when it has changed', async () => {
    mocked(persistenceService.readConfig).mockResolvedValueOnce({
      found: true,
      data: {
        themeSource: -1,
      },
    });
    await configChangedCallback();
    expect(config.themeSource).not.toBe(-1);
  });

  it('should handle config writing errors gracefully', async () => {
    mocked(persistenceService.readConfig).mockRejectedValue(new Error('boo'));
    await configChangedCallback();
  });

  describe('when it was disposed', () => {
    beforeEach(() => {
      sutDisposer();
    });

    it('should dispose the watcher', () => {
      expect(watcherDisposer).toBeCalled();
    });

    it('should not listen to store changes any more', () => {
      config.setThemeSource('dark');
      jest.advanceTimersByTime(2 * throttleMs);
      expect(persistenceService.writeConfig).not.toBeCalled();
    });
  });
});