« get me outta code hell

content-function.js « lib « test - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/test/lib/content-function.js
blob: cd86e9bcec567d9f03f7e369c5efd6a4b73c09c3 (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
import * as path from 'node:path';
import {fileURLToPath} from 'node:url';

import chroma from 'chroma-js';

import {getColors} from '#colors';
import {quickLoadContentDependencies} from '#content-dependencies';
import {quickEvaluate} from '#content-function';
import * as html from '#html';
import {processLanguageFile} from '#language';
import {empty, showAggregate} from '#sugar';
import {generateURLs, thumb, urlSpec} from '#urls';

import mock from './generic-mock.js';

const __dirname = path.dirname(fileURLToPath(import.meta.url));

export function testContentFunctions(t, message, fn) {
  const urls = generateURLs(urlSpec);

  t.test(message, async t => {
    let loadedContentDependencies;

    const language = await processLanguageFile('./src/strings-default.json');
    const mocks = [];

    const evaluate = ({
      from = 'localized.home',
      contentDependencies = {},
      extraDependencies = {},
      ...opts
    }) => {
      if (!loadedContentDependencies) {
        throw new Error(`Await .load() before performing tests`);
      }

      const {to} = urls.from(from);

      return cleanCatchAggregate(() => {
        return quickEvaluate({
          ...opts,
          contentDependencies: {
            ...contentDependencies,
            ...loadedContentDependencies,
          },
          extraDependencies: {
            html,
            language,
            thumb,
            to,
            urls,

            appendIndexHTML: false,

            getColors: c => getColors(c, {chroma}),
            getDimensionsOfImagePath: () => [600, 600],
            getThumbnailEqualOrSmaller: () => 'medium',
            getThumbnailsAvailableForDimensions: () =>
              [['large', 800], ['medium', 400], ['small', 250]],

            ...extraDependencies,
          },
        });
      });
    };

    evaluate.load = async (opts) => {
      if (loadedContentDependencies) {
        throw new Error(`Already loaded!`);
      }

      loadedContentDependencies = await asyncCleanCatchAggregate(() =>
        quickLoadContentDependencies({
          logging: false,
          ...opts,
        }));
    };

    evaluate.snapshot = (...args) => {
      if (!loadedContentDependencies) {
        throw new Error(`Await .load() before performing tests`);
      }

      const [description, opts] =
        (typeof args[0] === 'string'
          ? args
          : ['output', ...args]);

      let result = evaluate(opts);

      if (opts.multiple) {
        result = result.map(item => item.toString()).join('\n');
      } else {
        result = result.toString();
      }

      t.matchSnapshot(result, description);
    };

    evaluate.stubTemplate = name => {
      // Creates a particularly permissable template, allowing any slot values
      // to be stored and just outputting the contents of those slots as-are.

      return new (class extends html.Template {
        #slotValues = {};

        constructor() {
          super({
            content: () => `${name}: ${JSON.stringify(this.#slotValues)}`,
          });
        }

        setSlots(slotNamesToValues) {
          Object.assign(this.#slotValues, slotNamesToValues);
        }

        setSlot(slotName, slotValue) {
          this.#slotValues[slotName] = slotValue;
        }
      });
    };

    evaluate.mock = (...opts) => {
      const {value, close} = mock(...opts);
      mocks.push({close});
      return value;
    };

    evaluate.mock.transformContent = {
      transformContent: {
        extraDependencies: ['html'],
        data: content => ({content}),
        slots: {mode: {type: 'string'}},
        generate: ({content}) => content,
      },
    };

    await fn(t, evaluate);

    if (!empty(mocks)) {
      cleanCatchAggregate(() => {
        const errors = [];
        for (const {close} of mocks) {
          try {
            close();
          } catch (error) {
            errors.push(error);
          }
        }
        if (!empty(errors)) {
          throw new AggregateError(errors, `Errors closing mocks`);
        }
      });
    }
  });
}

function printAggregate(error) {
  if (error instanceof AggregateError) {
    const message = showAggregate(error, {
      showTraces: true,
      print: false,
      pathToFileURL: f => path.relative(path.join(__dirname, '../..'), fileURLToPath(f)),
    });
    for (const line of message.split('\n')) {
      console.error(line);
    }
  }
}

function cleanCatchAggregate(fn) {
  try {
    return fn();
  } catch (error) {
    printAggregate(error);
    throw error;
  }
}

async function asyncCleanCatchAggregate(fn) {
  try {
    return await fn();
  } catch (error) {
    printAggregate(error);
    throw error;
  }
}