« get me outta code hell

black-box.js « contract « unit « test - hsmusic-wiki - HSMusic - static wiki software cataloguing collaborative creation
about summary refs log tree commit diff
path: root/test/unit/contract/black-box.js
blob: 21c05b52b33fac36376bcec18efbfaa46dd71b69 (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
import {BlackBox} from '../../../src/contract.js';
import {mockFunction} from '../../lib/generic-mock.js';
import {showAggregate} from '../../../src/util/sugar.js';

import t from 'tap';

t.test(`BlackBox - caching`, t => {
  t.plan(8);

  const obj1 = {foo: 3, bar: 4};
  const obj2 = {baz: 5, qux: 6};

  let {value: fn, close: closeMock} =
    mockFunction((object, key) => object[key] ** 2)

  fn = fn
    .args([obj1, 'foo']).next()
    .args([obj2, 'qux']).next()
    .args([obj1, 'bar']).next()
    .args([obj2, 'baz']);

  const bb = new BlackBox(fn);
  const evaluate = bb.getEvaluator();

  t.equal(evaluate(obj1, 'foo'), 3 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);
  t.equal(evaluate(obj2, 'qux'), 6 ** 2);
  t.equal(evaluate(obj2, 'qux'), 6 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);

  t.equal(evaluate(obj1, 'bar'), 4 ** 2);
  t.equal(evaluate(obj2, 'baz'), 5 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);

  try {
    closeMock();
  } catch (error) {
    showAggregate(error);
    throw error;
  }
});

t.test(`BlackBox - no caching`, t => {
  t.plan(8);

  const obj1 = {foo: 3, bar: 4};
  const obj2 = {baz: 5, qux: 6};

  let {value: fn, close: closeMock} =
    mockFunction((object, key) => object[key] ** 2)

  fn = fn
    .args([obj1, 'foo']).repeat(2)
    .args([obj2, 'qux']).repeat(2)
    .args([obj1, 'foo']).next()
    .args([obj1, 'bar']).next()
    .args([obj2, 'baz']).next()
    .args([obj1, 'foo']);

  const bb = new BlackBox(fn);
  const evaluate = bb.getEvaluator();

  bb.caching = false;

  t.equal(evaluate(obj1, 'foo'), 3 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);
  t.equal(evaluate(obj2, 'qux'), 6 ** 2);
  t.equal(evaluate(obj2, 'qux'), 6 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);

  t.equal(evaluate(obj1, 'bar'), 4 ** 2);
  t.equal(evaluate(obj2, 'baz'), 5 ** 2);
  t.equal(evaluate(obj1, 'foo'), 3 ** 2);

  try {
    closeMock();
  } catch (error) {
    showAggregate(error);
    throw error;
  }
});