« 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: 30fa78e049a2a621ee8b70b22471b6018a1ff064 (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
import chroma from 'chroma-js';
import * as path from 'path';
import {fileURLToPath} from 'url';

import mock from './generic-mock.js';
import {quickEvaluate} from '../../src/content-function.js';
import {quickLoadContentDependencies} from '../../src/content/dependencies/index.js';

import urlSpec from '../../src/url-spec.js';
import * as html from '../../src/util/html.js';
import {empty, showAggregate} from '../../src/util/sugar.js';
import {getColors} from '../../src/util/colors.js';
import {generateURLs, thumb} from '../../src/util/urls.js';
import {processLanguageFile} from '../../src/data/language.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}),
            ...extraDependencies,
          },
        });
      });
    };

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

      loadedContentDependencies = await asyncCleanCatchAggregate(() =>
        quickLoadContentDependencies(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.mock = (...opts) => {
      const {value, close} = mock(...opts);
      mocks.push({close});
      return value;
    };

    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;
  }
}