Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] Add module for writing unit tests #121

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions modules.json
Original file line number Diff line number Diff line change
Expand Up @@ -111,5 +111,10 @@
},
"communication": {
"tabs": []
},
"testing": {
"tabs": [
"Testing"
]
podocarp marked this conversation as resolved.
Show resolved Hide resolved
}
}
48 changes: 48 additions & 0 deletions src/bundles/testing/__tests__/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import * as asserts from '../asserts';
import * as testing from '../functions';
import { list } from '../list';

beforeAll(() => {
testing.context.suiteResults = {
name: '',
results: [],
total: 0,
passed: 0,
};
testing.context.allResults.results = [];
testing.context.runtime = 0;
});

test('context is created correctly', () => {
const mockTestFn = jest.fn();
testing.describe('Testing 321', () => {
testing.it('Testing 123', mockTestFn);
});
expect(testing.context.suiteResults.passed).toEqual(1);
expect(mockTestFn).toHaveBeenCalled();
});

test('context fails correctly', () => {
testing.describe('Testing 123', () => {
testing.it('This test fails!', () => asserts.assert_equals(0, 1));
});
expect(testing.context.suiteResults.passed).toEqual(0);
expect(testing.context.suiteResults.total).toEqual(1);
});

test('assert works', () => {
expect(() => asserts.assert(() => true)).not.toThrow();
expect(() => asserts.assert(() => false)).toThrow('Assert failed');
});

test('assert_equals works', () => {
expect(() => asserts.assert_equals(1, 1)).not.toThrow();
expect(() => asserts.assert_equals(0, 1)).toThrow('Expected');
expect(() => asserts.assert_equals(1.00000000001, 1)).not.toThrow();
});

test('assert_contains works', () => {
const list1 = list(1, 2, 3);
expect(() => asserts.assert_contains(list1, 2)).not.toThrow();
expect(() => asserts.assert_contains(list1, 10)).toThrow();
});
85 changes: 85 additions & 0 deletions src/bundles/testing/asserts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { is_pair, head, tail, is_list, is_null, member, length } from './list';

/**
* Asserts that a predicate returns true.
* @param pred An predicate function that returns true/false.
* @returns
*/
export function assert(pred: () => boolean) {
if (!pred()) {
throw new Error('Assert failed!');
}
}

/**
* Asserts the equality (===) of two parameters.
* @param expected The expected value.
* @param received The given value.
* @returns
*/
export function assert_equals(expected: any, received: any) {
const fail = () => {
throw new Error(`Expected \`${expected}\`, got \`${received}\`!`);
};
if (typeof expected !== typeof received) {
fail();
}
// approx checking for floats
if (typeof expected === 'number' && !Number.isInteger(expected)) {
if (Math.abs(expected - received) > 0.001) {
fail();
} else {
return;
}
}
if (expected !== received) {
fail();
}
}

/**
* Asserts that `xs` contains `toContain`.
* @param xs The list to assert.
* @param toContain The element that `xs` is expected to contain.
*/
export function assert_contains(xs: any, toContain: any) {
const fail = () => {
throw new Error(`Expected \`${xs}\` to contain \`${toContain}\`.`);
};

if (is_null(xs)) {
fail();
} else if (is_list(xs)) {
if (is_null(member(toContain, xs))) {
fail();
}
} else if (is_pair(xs)) {
if (head(xs) === toContain || tail(xs) === toContain) {
return;
}

// check the head, if it fails, checks the tail, if that fails, fail.
try {
assert_contains(head(xs), toContain);
return;
} catch (_) {
try {
assert_contains(tail(xs), toContain);
return;
} catch (__) {
fail();
}
}
} else {
throw new Error(`First argument must be a list or a pair, got \`${xs}\`.`);
}
}

/**
* Asserts that the given list has length `len`.
* @param list The list to assert.
* @param len The expected length of the list.
*/
export function assert_length(list: any, len: number) {
assert_equals(length(list), len);
}
82 changes: 82 additions & 0 deletions src/bundles/testing/functions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { TestContext, TestSuite, Test } from './types';

const handleErr = (err: any) => {
if (err.error && err.error.message) {
return (err.error as Error).message;
}
if (err.message) {
return (err as Error).message;
}
throw err;
};

export const context: TestContext = {
describe: (msg: string, suite: TestSuite) => {
const starttime = performance.now();
context.suiteResults = {
name: msg,
results: [],
total: 0,
passed: 0,
};

suite();

context.allResults.results.push(context.suiteResults);

const endtime = performance.now();
context.runtime += endtime - starttime;
return context.allResults;
},

it: (msg: string, test: Test) => {
const name = `${msg}`;
let error = '';
context.suiteResults.total += 1;

try {
test();
context.suiteResults.passed += 1;
} catch (err: any) {
error = handleErr(err);
}

context.suiteResults.results.push({
name,
error,
});
},

suiteResults: {
name: '',
results: [],
total: 0,
passed: 0,
},

allResults: {
results: [],
toReplString: () =>
`${context.allResults.results.length} suites completed in ${context.runtime} ms.`,
},

runtime: 0,
};

/**
* Defines a single test.
* @param str Description for this test.
* @param func Function containing tests.
*/
export function it(msg: string, func: Test) {
context.it(msg, func);
}

/**
* Describes a test suite.
* @param str Description for this test.
* @param func Function containing tests.
*/
export function describe(msg: string, func: TestSuite) {
return context.describe(msg, func);
}
41 changes: 41 additions & 0 deletions src/bundles/testing/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import {
assert_equals,
assert_not_equals,
assert_contains,
assert_approx_equals,
assert_greater,
assert_greater_equals,
assert_length,
} from './asserts';
import { it, describe } from './functions';
import { mock_fn } from './mocks';

/**
* Collection of unit-testing tools for Source.
* @author Jia Xiaodong
*/

/**
* Increment a number by a value of 1.
* @param x the number to be incremented
* @returns the incremented value of the number
*/
function sample_function(x: number) {
return x + 1;
}

// Un-comment the next line if your bundle requires the use of variables
// declared in cadet-frontend or js-slang.
export default () => ({
sample_function,
it,
describe,
assert_equals,
assert_not_equals,
assert_contains,
assert_greater,
assert_greater_equals,
assert_approx_equals,
assert_length,
mock_fn,
});
Loading
Loading