From 4c28fa1ce386f694d7ca83f351d4ff1bb6fe6f30 Mon Sep 17 00:00:00 2001 From: Christoph Knittel Date: Tue, 22 Oct 2024 17:19:00 +0200 Subject: [PATCH] Add Core tests (#7116) * Add Core tests * No open RescriptCore * Fix imports * Build Core tests * Fix test * Run Core tests in CI * CHANGELOG --- CHANGELOG.md | 2 +- scripts/test.js | 12 +- tests/tests/src/core/Core_ArrayTests.mjs | 463 ++++++++++++ tests/tests/src/core/Core_ArrayTests.res | 111 +++ tests/tests/src/core/Core_DictTests.mjs | 57 ++ tests/tests/src/core/Core_DictTests.res | 18 + tests/tests/src/core/Core_ErrorTests.mjs | 36 + tests/tests/src/core/Core_ErrorTests.res | 9 + tests/tests/src/core/Core_FloatTests.mjs | 253 +++++++ tests/tests/src/core/Core_FloatTests.res | 47 ++ tests/tests/src/core/Core_ImportTests.mjs | 21 + tests/tests/src/core/Core_ImportTests.res | 6 + tests/tests/src/core/Core_IntTests.mjs | 560 ++++++++++++++ tests/tests/src/core/Core_IntTests.res | 168 +++++ tests/tests/src/core/Core_IteratorTests.mjs | 113 +++ tests/tests/src/core/Core_IteratorTests.res | 67 ++ tests/tests/src/core/Core_JsonTests.mjs | 45 ++ tests/tests/src/core/Core_JsonTests.res | 20 + tests/tests/src/core/Core_NullableTests.mjs | 49 ++ tests/tests/src/core/Core_NullableTests.res | 37 + tests/tests/src/core/Core_ObjectTests.mjs | 609 ++++++++++++++++ tests/tests/src/core/Core_ObjectTests.res | 177 +++++ tests/tests/src/core/Core_PromiseTest.mjs | 684 ++++++++++++++++++ tests/tests/src/core/Core_PromiseTest.res | 449 ++++++++++++ tests/tests/src/core/Core_ResultTests.mjs | 92 +++ tests/tests/src/core/Core_ResultTests.res | 32 + tests/tests/src/core/Core_StringTests.mjs | 21 + tests/tests/src/core/Core_StringTests.res | 3 + tests/tests/src/core/Core_TempTests.mjs | 363 ++++++++++ tests/tests/src/core/Core_TempTests.res | 196 +++++ tests/tests/src/core/Core_TestSuite.mjs | 121 ++++ tests/tests/src/core/Core_TestSuite.res | 13 + tests/tests/src/core/Core_TestTests.mjs | 188 +++++ tests/tests/src/core/Core_TestTests.res | 26 + tests/tests/src/core/Core_TypedArrayTests.mjs | 101 +++ tests/tests/src/core/Core_TypedArrayTests.res | 74 ++ tests/tests/src/core/Test.mjs | 53 ++ tests/tests/src/core/Test.res | 50 ++ tests/tests/src/core/intl/Core_IntlTests.mjs | 130 ++++ tests/tests/src/core/intl/Core_IntlTests.res | 51 ++ .../src/core/intl/Core_Intl_CollatorTest.mjs | 46 ++ .../src/core/intl/Core_Intl_CollatorTest.res | 16 + .../intl/Core_Intl_DateTimeFormatTest.mjs | 89 +++ .../intl/Core_Intl_DateTimeFormatTest.res | 56 ++ .../core/intl/Core_Intl_ListFormatTest.mjs | 58 ++ .../core/intl/Core_Intl_ListFormatTest.res | 17 + .../src/core/intl/Core_Intl_LocaleTest.mjs | 46 ++ .../src/core/intl/Core_Intl_LocaleTest.res | 27 + .../core/intl/Core_Intl_NumberFormatTest.mjs | 58 ++ .../core/intl/Core_Intl_NumberFormatTest.res | 43 ++ .../core/intl/Core_Intl_PluralRulesTest.mjs | 37 + .../core/intl/Core_Intl_PluralRulesTest.res | 33 + .../intl/Core_Intl_RelativeTimeFormatTest.mjs | 47 ++ .../intl/Core_Intl_RelativeTimeFormatTest.res | 29 + .../src/core/intl/Core_Intl_SegmenterTest.mjs | 50 ++ .../src/core/intl/Core_Intl_SegmenterTest.res | 27 + 56 files changed, 6204 insertions(+), 2 deletions(-) create mode 100644 tests/tests/src/core/Core_ArrayTests.mjs create mode 100644 tests/tests/src/core/Core_ArrayTests.res create mode 100644 tests/tests/src/core/Core_DictTests.mjs create mode 100644 tests/tests/src/core/Core_DictTests.res create mode 100644 tests/tests/src/core/Core_ErrorTests.mjs create mode 100644 tests/tests/src/core/Core_ErrorTests.res create mode 100644 tests/tests/src/core/Core_FloatTests.mjs create mode 100644 tests/tests/src/core/Core_FloatTests.res create mode 100644 tests/tests/src/core/Core_ImportTests.mjs create mode 100644 tests/tests/src/core/Core_ImportTests.res create mode 100644 tests/tests/src/core/Core_IntTests.mjs create mode 100644 tests/tests/src/core/Core_IntTests.res create mode 100644 tests/tests/src/core/Core_IteratorTests.mjs create mode 100644 tests/tests/src/core/Core_IteratorTests.res create mode 100644 tests/tests/src/core/Core_JsonTests.mjs create mode 100644 tests/tests/src/core/Core_JsonTests.res create mode 100644 tests/tests/src/core/Core_NullableTests.mjs create mode 100644 tests/tests/src/core/Core_NullableTests.res create mode 100644 tests/tests/src/core/Core_ObjectTests.mjs create mode 100644 tests/tests/src/core/Core_ObjectTests.res create mode 100644 tests/tests/src/core/Core_PromiseTest.mjs create mode 100644 tests/tests/src/core/Core_PromiseTest.res create mode 100644 tests/tests/src/core/Core_ResultTests.mjs create mode 100644 tests/tests/src/core/Core_ResultTests.res create mode 100644 tests/tests/src/core/Core_StringTests.mjs create mode 100644 tests/tests/src/core/Core_StringTests.res create mode 100644 tests/tests/src/core/Core_TempTests.mjs create mode 100644 tests/tests/src/core/Core_TempTests.res create mode 100644 tests/tests/src/core/Core_TestSuite.mjs create mode 100644 tests/tests/src/core/Core_TestSuite.res create mode 100644 tests/tests/src/core/Core_TestTests.mjs create mode 100644 tests/tests/src/core/Core_TestTests.res create mode 100644 tests/tests/src/core/Core_TypedArrayTests.mjs create mode 100644 tests/tests/src/core/Core_TypedArrayTests.res create mode 100644 tests/tests/src/core/Test.mjs create mode 100644 tests/tests/src/core/Test.res create mode 100644 tests/tests/src/core/intl/Core_IntlTests.mjs create mode 100644 tests/tests/src/core/intl/Core_IntlTests.res create mode 100644 tests/tests/src/core/intl/Core_Intl_CollatorTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_CollatorTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_ListFormatTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_ListFormatTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_LocaleTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_LocaleTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_NumberFormatTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_NumberFormatTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_PluralRulesTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_PluralRulesTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.res create mode 100644 tests/tests/src/core/intl/Core_Intl_SegmenterTest.mjs create mode 100644 tests/tests/src/core/intl/Core_Intl_SegmenterTest.res diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c4d4ed6b9..197676323f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,7 +24,7 @@ - Allow spreads of variants in patterns (`| ...someVariant as v => `) when the variant spread is a subtype of the variant matched on. https://github.com/rescript-lang/rescript-compiler/pull/6721 - Fix the issue where dynamic imports are not working for function-defined externals. https://github.com/rescript-lang/rescript-compiler/pull/7060 - Allow pattern matching on dicts. `switch someDict { | dict{"one": 1} => Js.log("one is one") }`. https://github.com/rescript-lang/rescript-compiler/pull/7059 -- "ReScript Core" standard library is now included in the `rescript` npm package. https://github.com/rescript-lang/rescript-compiler/pull/7108 +- "ReScript Core" standard library is now included in the `rescript` npm package. https://github.com/rescript-lang/rescript-compiler/pull/7108 https://github.com/rescript-lang/rescript-compiler/pull/7116 - Handle absolute filepaths in gentype. https://github.com/rescript-lang/rescript-compiler/pull/7104 #### :bug: Bug fix diff --git a/scripts/test.js b/scripts/test.js index f55482b211..f9f10465f0 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -65,7 +65,17 @@ async function runTests() { stdio: [0, 1, 2], }); - cp.execSync(`npx mocha -t 10000 tests/tests/**/*_test.mjs`, { + cp.execSync("npx mocha -t 10000 tests/tests/**/*_test.mjs", { + cwd: path.join(__dirname, ".."), + stdio: [0, 1, 2], + }); + + cp.execSync("node tests/tests/src/core/Core_TestSuite.mjs", { + cwd: path.join(__dirname, ".."), + stdio: [0, 1, 2], + }); + + cp.execSync("node tests/tests/src/core/Core_TempTests.mjs", { cwd: path.join(__dirname, ".."), stdio: [0, 1, 2], }); diff --git a/tests/tests/src/core/Core_ArrayTests.mjs b/tests/tests/src/core/Core_ArrayTests.mjs new file mode 100644 index 0000000000..5f48457d79 --- /dev/null +++ b/tests/tests/src/core/Core_ArrayTests.mjs @@ -0,0 +1,463 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as List from "rescript/lib/es6/List.js"; +import * as Test from "./Test.mjs"; +import * as $$Array from "rescript/lib/es6/Array.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_ArrayTests.res", + 3, + 20, + 26 + ], + "make" +], $$Array.make(6, 7), eq, [ + 7, + 7, + 7, + 7, + 7, + 7 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 5, + 20, + 42 + ], + "getUnsafe - existing" +], 1, eq, 1); + +Test.run([ + [ + "Core_ArrayTests.res", + 6, + 20, + 41 + ], + "getUnsafe - missing" +], [ + 0, + 1, + 2 + ][10], eq, undefined); + +Test.run([ + [ + "Core_ArrayTests.res", + 9, + 13, + 30 + ], + "fromInitializer" +], $$Array.fromInitializer(7, i => i + 3 | 0), eq, [ + 3, + 4, + 5, + 6, + 7, + 8, + 9 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 15, + 20, + 28 + ], + "reduce" +], $$Array.reduce([ + 1, + 2, + 3 +], /* [] */0, List.add), eq, { + hd: 3, + tl: { + hd: 2, + tl: { + hd: 1, + tl: /* [] */0 + } + } +}); + +Test.run([ + [ + "Core_ArrayTests.res", + 16, + 20, + 36 + ], + "reduce - empty" +], $$Array.reduce([], /* [] */0, List.add), eq, /* [] */0); + +Test.run([ + [ + "Core_ArrayTests.res", + 19, + 13, + 30 + ], + "reduceWithIndex" +], $$Array.reduceWithIndex([ + 1, + 2, + 3 +], /* [] */0, (acc, v, i) => ({ + hd: v + i | 0, + tl: acc +})), eq, { + hd: 5, + tl: { + hd: 3, + tl: { + hd: 1, + tl: /* [] */0 + } + } +}); + +Test.run([ + [ + "Core_ArrayTests.res", + 25, + 13, + 38 + ], + "reduceWithIndex - empty" +], $$Array.reduceWithIndex([], /* [] */0, (acc, v, i) => ({ + hd: v + i | 0, + tl: acc +})), eq, /* [] */0); + +Test.run([ + [ + "Core_ArrayTests.res", + 32, + 13, + 26 + ], + "reduceRight" +], $$Array.reduceRight([ + 1, + 2, + 3 +], /* [] */0, List.add), eq, { + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}); + +Test.run([ + [ + "Core_ArrayTests.res", + 37, + 20, + 41 + ], + "reduceRight - empty" +], $$Array.reduceRight([], /* [] */0, List.add), eq, /* [] */0); + +Test.run([ + [ + "Core_ArrayTests.res", + 40, + 13, + 35 + ], + "reduceEightWithIndex" +], $$Array.reduceRightWithIndex([ + 1, + 2, + 3 +], /* [] */0, (acc, v, i) => ({ + hd: v + i | 0, + tl: acc +})), eq, { + hd: 1, + tl: { + hd: 3, + tl: { + hd: 5, + tl: /* [] */0 + } + } +}); + +Test.run([ + [ + "Core_ArrayTests.res", + 46, + 13, + 38 + ], + "reduceWithIndex - empty" +], $$Array.reduceRightWithIndex([], /* [] */0, (acc, v, i) => ({ + hd: v + i | 0, + tl: acc +})), eq, /* [] */0); + +Test.run([ + [ + "Core_ArrayTests.res", + 52, + 20, + 41 + ], + "toShuffled - length" +], $$Array.toShuffled([ + 1, + 2, + 3 +]).length, eq, 3); + +let arr = [ + 1, + 2, + 3 +]; + +Test.run([ + [ + "Core_ArrayTests.res", + 55, + 13, + 31 + ], + "shuffle - length" +], ($$Array.shuffle(arr), arr.length), eq, 3); + +Test.run([ + [ + "Core_ArrayTests.res", + 66, + 13, + 24 + ], + "filterMap" +], $$Array.filterMap([ + 1, + 2, + 3, + 4, + 5, + 6 +], n => { + if (n % 2 === 0) { + return Math.imul(n, n); + } + +}), eq, [ + 4, + 16, + 36 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 71, + 20, + 42 + ], + "filterMap - no match" +], $$Array.filterMap([ + 1, + 2, + 3, + 4, + 5, + 6 +], param => {}), eq, []); + +Test.run([ + [ + "Core_ArrayTests.res", + 73, + 13, + 32 + ], + "filterMap - empty" +], $$Array.filterMap([], n => { + if (n % 2 === 0) { + return Math.imul(n, n); + } + +}), eq, []); + +Test.run([ + [ + "Core_ArrayTests.res", + 79, + 20, + 30 + ], + "keepSome" +], $$Array.keepSome([ + 1, + undefined, + 3 +]), eq, [ + 1, + 3 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 81, + 13, + 34 + ], + "keepSome - all Some" +], $$Array.keepSome([ + 1, + 2, + 3 +]), eq, [ + 1, + 2, + 3 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 86, + 20, + 41 + ], + "keepSome - all None" +], $$Array.keepSome([ + undefined, + undefined, + undefined +]), eq, []); + +Test.run([ + [ + "Core_ArrayTests.res", + 87, + 20, + 38 + ], + "keepSome - empty" +], $$Array.keepSome([]), eq, []); + +Test.run([ + [ + "Core_ArrayTests.res", + 90, + 13, + 22 + ], + "findMap" +], $$Array.findMap([ + 1, + 2, + 3, + 4, + 5, + 6 +], n => { + if (n % 2 === 0) { + return n - 8 | 0; + } + +}), eq, -6); + +Test.run([ + [ + "Core_ArrayTests.res", + 95, + 20, + 40 + ], + "findMap - no match" +], $$Array.findMap([ + 1, + 2, + 3, + 4, + 5, + 6 +], param => {}), eq, undefined); + +Test.run([ + [ + "Core_ArrayTests.res", + 97, + 13, + 30 + ], + "findMap - empty" +], $$Array.findMap([], n => { + if (n % 2 === 0) { + return Math.imul(n, n); + } + +}), eq, undefined); + +Test.run([ + [ + "Core_ArrayTests.res", + 104, + 13, + 27 + ], + "fromIterator" +], Array.from(new Map([ + [ + 1, + 3 + ], + [ + 2, + 4 + ] +]).values()), eq, [ + 3, + 4 +]); + +Test.run([ + [ + "Core_ArrayTests.res", + 110, + 20, + 39 + ], + "last - with items" +], $$Array.last([ + 1, + 2, + 3 +]), eq, 3); + +Test.run([ + [ + "Core_ArrayTests.res", + 111, + 20, + 34 + ], + "last - empty" +], $$Array.last([]), eq, undefined); + +export { + eq, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_ArrayTests.res b/tests/tests/src/core/Core_ArrayTests.res new file mode 100644 index 0000000000..01fdf39c34 --- /dev/null +++ b/tests/tests/src/core/Core_ArrayTests.res @@ -0,0 +1,111 @@ +let eq = (a, b) => a == b + +Test.run(__POS_OF__("make"), Array.make(~length=6, 7), eq, [7, 7, 7, 7, 7, 7]) + +Test.run(__POS_OF__("getUnsafe - existing"), [0, 1, 2]->Array.getUnsafe(1), eq, 1) +Test.run(__POS_OF__("getUnsafe - missing"), [0, 1, 2]->Array.getUnsafe(10), eq, %raw(`undefined`)) + +Test.run( + __POS_OF__("fromInitializer"), + Array.fromInitializer(~length=7, i => i + 3), + eq, + [3, 4, 5, 6, 7, 8, 9], +) + +Test.run(__POS_OF__("reduce"), Array.reduce([1, 2, 3], list{}, List.add), eq, list{3, 2, 1}) +Test.run(__POS_OF__("reduce - empty"), Array.reduce([], list{}, List.add), eq, list{}) + +Test.run( + __POS_OF__("reduceWithIndex"), + Array.reduceWithIndex([1, 2, 3], list{}, (acc, v, i) => list{v + i, ...acc}), + eq, + list{5, 3, 1}, +) +Test.run( + __POS_OF__("reduceWithIndex - empty"), + Array.reduceWithIndex([], list{}, (acc, v, i) => list{v + i, ...acc}), + eq, + list{}, +) + +Test.run( + __POS_OF__("reduceRight"), + Array.reduceRight([1, 2, 3], list{}, List.add), + eq, + list{1, 2, 3}, +) +Test.run(__POS_OF__("reduceRight - empty"), Array.reduceRight([], list{}, List.add), eq, list{}) + +Test.run( + __POS_OF__("reduceEightWithIndex"), + Array.reduceRightWithIndex([1, 2, 3], list{}, (acc, v, i) => list{v + i, ...acc}), + eq, + list{1, 3, 5}, +) +Test.run( + __POS_OF__("reduceWithIndex - empty"), + Array.reduceRightWithIndex([], list{}, (acc, v, i) => list{v + i, ...acc}), + eq, + list{}, +) + +Test.run(__POS_OF__("toShuffled - length"), Array.toShuffled([1, 2, 3])->Array.length, eq, 3) + +Test.run( + __POS_OF__("shuffle - length"), + { + let arr = [1, 2, 3] + Array.shuffle(arr) + arr->Array.length + }, + eq, + 3, +) + +Test.run( + __POS_OF__("filterMap"), + Array.filterMap([1, 2, 3, 4, 5, 6], n => mod(n, 2) == 0 ? Some(n * n) : None), + eq, + [4, 16, 36], +) +Test.run(__POS_OF__("filterMap - no match"), Array.filterMap([1, 2, 3, 4, 5, 6], _ => None), eq, []) +Test.run( + __POS_OF__("filterMap - empty"), + Array.filterMap([], n => mod(n, 2) == 0 ? Some(n * n) : None), + eq, + [], +) + +Test.run(__POS_OF__("keepSome"), Array.keepSome([Some(1), None, Some(3)]), eq, [1, 3]) +Test.run( + __POS_OF__("keepSome - all Some"), + Array.keepSome([Some(1), Some(2), Some(3)]), + eq, + [1, 2, 3], +) +Test.run(__POS_OF__("keepSome - all None"), Array.keepSome([None, None, None]), eq, []) +Test.run(__POS_OF__("keepSome - empty"), Array.keepSome([]), eq, []) + +Test.run( + __POS_OF__("findMap"), + Array.findMap([1, 2, 3, 4, 5, 6], n => mod(n, 2) == 0 ? Some(n - 8) : None), + eq, + Some(-6), +) +Test.run(__POS_OF__("findMap - no match"), Array.findMap([1, 2, 3, 4, 5, 6], _ => None), eq, None) +Test.run( + __POS_OF__("findMap - empty"), + Array.findMap([], n => mod(n, 2) == 0 ? Some(n * n) : None), + eq, + None, +) + +Test.run( + __POS_OF__("fromIterator"), + Array.fromIterator(Map.fromArray([(1, 3), (2, 4)])->Map.values), + eq, + [3, 4], +) + +Test.run(__POS_OF__("last - with items"), [1, 2, 3]->Array.last, eq, Some(3)) +Test.run(__POS_OF__("last - empty"), []->Array.last, eq, None) diff --git a/tests/tests/src/core/Core_DictTests.mjs b/tests/tests/src/core/Core_DictTests.mjs new file mode 100644 index 0000000000..8efe14aada --- /dev/null +++ b/tests/tests/src/core/Core_DictTests.mjs @@ -0,0 +1,57 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_DictTests.res", + 3, + 20, + 26 + ], + "make" +], {}, eq, {}); + +Test.run([ + [ + "Core_DictTests.res", + 5, + 20, + 31 + ], + "fromArray" +], Object.fromEntries([[ + "foo", + "bar" + ]]), eq, {foo: "bar"}); + +Test.run([ + [ + "Core_DictTests.res", + 8, + 13, + 35 + ], + "getUnsafe - existing" +], Object.fromEntries([[ + "foo", + "bar" + ]])["foo"], eq, "bar"); + +Test.run([ + [ + "Core_DictTests.res", + 14, + 13, + 34 + ], + "getUnsafe - missing" +], ({})["foo"], eq, undefined); + +export { + eq, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_DictTests.res b/tests/tests/src/core/Core_DictTests.res new file mode 100644 index 0000000000..968dbab9ad --- /dev/null +++ b/tests/tests/src/core/Core_DictTests.res @@ -0,0 +1,18 @@ +let eq = (a, b) => a == b + +Test.run(__POS_OF__("make"), Dict.make(), eq, %raw(`{}`)) + +Test.run(__POS_OF__("fromArray"), Dict.fromArray([("foo", "bar")]), eq, %raw(`{foo: "bar"}`)) + +Test.run( + __POS_OF__("getUnsafe - existing"), + Dict.fromArray([("foo", "bar")])->Dict.getUnsafe("foo"), + eq, + "bar", +) +Test.run( + __POS_OF__("getUnsafe - missing"), + Dict.make()->Dict.getUnsafe("foo"), + eq, + %raw(`undefined`), +) diff --git a/tests/tests/src/core/Core_ErrorTests.mjs b/tests/tests/src/core/Core_ErrorTests.mjs new file mode 100644 index 0000000000..ce1cb6e63e --- /dev/null +++ b/tests/tests/src/core/Core_ErrorTests.mjs @@ -0,0 +1,36 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Exn from "rescript/lib/es6/Exn.js"; +import * as Test from "./Test.mjs"; +import * as Pervasives from "rescript/lib/es6/Pervasives.js"; +import * as Primitive_exceptions from "rescript/lib/es6/Primitive_exceptions.js"; + +function panicTest() { + let caught; + try { + caught = Pervasives.panic("uh oh"); + } catch (raw_err) { + let err = Primitive_exceptions.internalToException(raw_err); + if (err.RE_EXN_ID === Exn.$$Error) { + caught = err._1.message; + } else { + throw err; + } + } + Test.run([ + [ + "Core_ErrorTests.res", + 6, + 22, + 43 + ], + "Should resolve test" + ], caught, (prim0, prim1) => prim0 === prim1, "Panic! uh oh"); +} + +panicTest(); + +export { + panicTest, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_ErrorTests.res b/tests/tests/src/core/Core_ErrorTests.res new file mode 100644 index 0000000000..3113346495 --- /dev/null +++ b/tests/tests/src/core/Core_ErrorTests.res @@ -0,0 +1,9 @@ +let panicTest = () => { + let caught = try panic("uh oh") catch { + | Exn.Error(err) => Error.message(err) + } + + Test.run(__POS_OF__("Should resolve test"), caught, \"==", Some("Panic! uh oh")) +} + +panicTest() diff --git a/tests/tests/src/core/Core_FloatTests.mjs b/tests/tests/src/core/Core_FloatTests.mjs new file mode 100644 index 0000000000..f58ad653a9 --- /dev/null +++ b/tests/tests/src/core/Core_FloatTests.mjs @@ -0,0 +1,253 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Float from "rescript/lib/es6/Float.js"; +import * as Pervasives from "rescript/lib/es6/Pervasives.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_FloatTests.res", + 3, + 20, + 27 + ], + "clamp" +], Float.clamp(undefined, undefined, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 4, + 20, + 35 + ], + "clamp - < min" +], Float.clamp(4.3, undefined, 4.1), eq, 4.3); + +Test.run([ + [ + "Core_FloatTests.res", + 5, + 20, + 35 + ], + "clamp - > min" +], Float.clamp(4.1, undefined, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 6, + 20, + 35 + ], + "clamp - < max" +], Float.clamp(undefined, 4.3, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 7, + 20, + 35 + ], + "clamp - > max" +], Float.clamp(undefined, 4.1, 4.2), eq, 4.1); + +Test.run([ + [ + "Core_FloatTests.res", + 8, + 20, + 42 + ], + "clamp - < min, < max" +], Float.clamp(4.3, 4.5, 4.2), eq, 4.3); + +Test.run([ + [ + "Core_FloatTests.res", + 9, + 20, + 42 + ], + "clamp - < min, > max" +], Float.clamp(4.3, 4.1, 4.2), eq, 4.3); + +Test.run([ + [ + "Core_FloatTests.res", + 10, + 20, + 42 + ], + "clamp - > min, < max" +], Float.clamp(4.1, 4.5, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 11, + 20, + 42 + ], + "clamp - > min, > max" +], Float.clamp(4.1, 4.1, 4.2), eq, 4.1); + +Test.run([ + [ + "Core_FloatTests.res", + 12, + 20, + 33 + ], + "clamp - nan" +], isNaN(Float.clamp(4.1, 4.3, Number.NaN)), eq, true); + +Test.run([ + [ + "Core_FloatTests.res", + 13, + 20, + 38 + ], + "clamp - infinity" +], Float.clamp(4.1, 4.3, Pervasives.infinity), eq, 4.3); + +Test.run([ + [ + "Core_FloatTests.res", + 14, + 20, + 39 + ], + "clamp - -infinity" +], Float.clamp(4.1, 4.3, Pervasives.neg_infinity), eq, 4.1); + +Test.run([ + [ + "Core_FloatTests.res", + 15, + 20, + 37 + ], + "clamp - min nan" +], Float.clamp(Number.NaN, undefined, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 16, + 20, + 37 + ], + "clamp - max nan" +], Float.clamp(undefined, Number.NaN, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 17, + 20, + 46 + ], + "clamp - min nan, max nan" +], Float.clamp(Number.NaN, Number.NaN, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 18, + 20, + 42 + ], + "clamp - min infinity" +], Float.clamp(Pervasives.infinity, undefined, 4.2), eq, Pervasives.infinity); + +Test.run([ + [ + "Core_FloatTests.res", + 19, + 20, + 42 + ], + "clamp - max infinity" +], Float.clamp(undefined, Pervasives.infinity, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 20, + 20, + 43 + ], + "clamp - min -infinity" +], Float.clamp(Pervasives.neg_infinity, undefined, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 21, + 20, + 43 + ], + "clamp - max -infinity" +], Float.clamp(undefined, Pervasives.neg_infinity, 4.2), eq, Pervasives.neg_infinity); + +Test.run([ + [ + "Core_FloatTests.res", + 23, + 13, + 49 + ], + "clamp - min infinity, max infinity" +], Float.clamp(Pervasives.infinity, Pervasives.infinity, 4.2), eq, Pervasives.infinity); + +Test.run([ + [ + "Core_FloatTests.res", + 29, + 13, + 50 + ], + "clamp - min -infinity, max infinity" +], Float.clamp(Pervasives.neg_infinity, Pervasives.infinity, 4.2), eq, 4.2); + +Test.run([ + [ + "Core_FloatTests.res", + 35, + 13, + 50 + ], + "clamp - min infinity, max -infinity" +], Float.clamp(Pervasives.infinity, Pervasives.neg_infinity, 4.2), eq, Pervasives.infinity); + +Test.run([ + [ + "Core_FloatTests.res", + 41, + 13, + 51 + ], + "clamp - min -infinity, max -infinity" +], Float.clamp(Pervasives.neg_infinity, Pervasives.neg_infinity, 4.2), eq, Pervasives.neg_infinity); + +Test.run([ + [ + "Core_FloatTests.res", + 47, + 20, + 46 + ], + "Float.equal optimization" +], false, eq, false); + +export { + eq, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_FloatTests.res b/tests/tests/src/core/Core_FloatTests.res new file mode 100644 index 0000000000..1632c2dffa --- /dev/null +++ b/tests/tests/src/core/Core_FloatTests.res @@ -0,0 +1,47 @@ +let eq = (a, b) => a == b + +Test.run(__POS_OF__("clamp"), Float.clamp(4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - < min"), Float.clamp(~min=4.3, 4.1), eq, 4.3) +Test.run(__POS_OF__("clamp - > min"), Float.clamp(~min=4.1, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - < max"), Float.clamp(~max=4.3, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - > max"), Float.clamp(~max=4.1, 4.2), eq, 4.1) +Test.run(__POS_OF__("clamp - < min, < max"), Float.clamp(~min=4.3, ~max=4.5, 4.2), eq, 4.3) +Test.run(__POS_OF__("clamp - < min, > max"), Float.clamp(~min=4.3, ~max=4.1, 4.2), eq, 4.3) // min wins +Test.run(__POS_OF__("clamp - > min, < max"), Float.clamp(~min=4.1, ~max=4.5, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - > min, > max"), Float.clamp(~min=4.1, ~max=4.1, 4.2), eq, 4.1) +Test.run(__POS_OF__("clamp - nan"), Float.clamp(~min=4.1, ~max=4.3, nan)->Float.isNaN, eq, true) +Test.run(__POS_OF__("clamp - infinity"), Float.clamp(~min=4.1, ~max=4.3, infinity), eq, 4.3) +Test.run(__POS_OF__("clamp - -infinity"), Float.clamp(~min=4.1, ~max=4.3, neg_infinity), eq, 4.1) +Test.run(__POS_OF__("clamp - min nan"), Float.clamp(~min=nan, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - max nan"), Float.clamp(~max=nan, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - min nan, max nan"), Float.clamp(~min=nan, ~max=nan, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - min infinity"), Float.clamp(~min=infinity, 4.2), eq, infinity) +Test.run(__POS_OF__("clamp - max infinity"), Float.clamp(~max=infinity, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - min -infinity"), Float.clamp(~min=neg_infinity, 4.2), eq, 4.2) +Test.run(__POS_OF__("clamp - max -infinity"), Float.clamp(~max=neg_infinity, 4.2), eq, neg_infinity) +Test.run( + __POS_OF__("clamp - min infinity, max infinity"), + Float.clamp(~min=infinity, ~max=infinity, 4.2), + eq, + infinity, +) +Test.run( + __POS_OF__("clamp - min -infinity, max infinity"), + Float.clamp(~min=neg_infinity, ~max=infinity, 4.2), + eq, + 4.2, +) +Test.run( + __POS_OF__("clamp - min infinity, max -infinity"), + Float.clamp(~min=infinity, ~max=neg_infinity, 4.2), + eq, + infinity, // min wins +) +Test.run( + __POS_OF__("clamp - min -infinity, max -infinity"), + Float.clamp(~min=neg_infinity, ~max=neg_infinity, 4.2), + eq, + neg_infinity, +) + +Test.run(__POS_OF__("Float.equal optimization"), Float.equal(1., 3.), eq, false) diff --git a/tests/tests/src/core/Core_ImportTests.mjs b/tests/tests/src/core/Core_ImportTests.mjs new file mode 100644 index 0000000000..bdfc1180c3 --- /dev/null +++ b/tests/tests/src/core/Core_ImportTests.mjs @@ -0,0 +1,21 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; + +async function main() { + let eq = await import("./Core_IntTests.mjs").then(m => m.eq); + return Test.run([ + [ + "Core_ImportTests.res", + 3, + 22, + 55 + ], + "dynamic import - Int tests - eq" + ], 1, eq, 1); +} + +export { + main, +} +/* Test Not a pure module */ diff --git a/tests/tests/src/core/Core_ImportTests.res b/tests/tests/src/core/Core_ImportTests.res new file mode 100644 index 0000000000..e9e2049aff --- /dev/null +++ b/tests/tests/src/core/Core_ImportTests.res @@ -0,0 +1,6 @@ +let main = async () => { + let eq = await import(Core_IntTests.eq) + Test.run(__POS_OF__("dynamic import - Int tests - eq"), 1, eq, 1) +} + +main->ignore diff --git a/tests/tests/src/core/Core_IntTests.mjs b/tests/tests/src/core/Core_IntTests.mjs new file mode 100644 index 0000000000..6935d883e3 --- /dev/null +++ b/tests/tests/src/core/Core_IntTests.mjs @@ -0,0 +1,560 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Exn from "rescript/lib/es6/Exn.js"; +import * as Int from "rescript/lib/es6/Int.js"; +import * as Test from "./Test.mjs"; +import * as Pervasives from "rescript/lib/es6/Pervasives.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; +import * as Primitive_exceptions from "rescript/lib/es6/Primitive_exceptions.js"; + +let eq = Primitive_object.equal; + +function $$catch(f) { + try { + f(); + return Pervasives.failwith("no exception raised"); + } catch (raw_err) { + let err = Primitive_exceptions.internalToException(raw_err); + if (err.RE_EXN_ID === Exn.$$Error) { + return err._1; + } + throw err; + } +} + +Test.run([ + [ + "Core_IntTests.res", + 11, + 20, + 50 + ], + "range - positive, increasing" +], Int.range(3, 6, undefined), eq, [ + 3, + 4, + 5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 12, + 20, + 50 + ], + "range - negative, increasing" +], Int.range(-3, -1, undefined), eq, [ + -3, + -2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 13, + 20, + 51 + ], + "range - cross-zero, incresing" +], Int.range(-1, 2, undefined), eq, [ + -1, + 0, + 1 +]); + +Test.run([ + [ + "Core_IntTests.res", + 14, + 20, + 42 + ], + "range - start == end" +], Int.range(3, 3, undefined), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 15, + 20, + 50 + ], + "range - positive, decreasing" +], Int.range(3, 1, undefined), eq, [ + 3, + 2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 16, + 20, + 50 + ], + "range - negative, decreasing" +], Int.range(-1, -3, undefined), eq, [ + -1, + -2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 19, + 13, + 51 + ], + "range - positive, increasing, step 2" +], Int.range(3, 6, { + step: 2 +}), eq, [ + 3, + 5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 25, + 13, + 51 + ], + "range + positive, increasing, step 2" +], Int.range(3, 7, { + step: 2 +}), eq, [ + 3, + 5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 31, + 13, + 51 + ], + "range + positive, increasing, step 2" +], Int.range(3, 8, { + step: 2 +}), eq, [ + 3, + 5, + 7 +]); + +Test.run([ + [ + "Core_IntTests.res", + 37, + 13, + 51 + ], + "range - negative, increasing, step 2" +], Int.range(-6, -3, { + step: 2 +}), eq, [ + -6, + -4 +]); + +Test.run([ + [ + "Core_IntTests.res", + 43, + 13, + 51 + ], + "range - positive, increasing, step 0" +], $$catch(() => Int.range(3, 6, { + step: 0 +})), eq, new RangeError("Incorrect range arguments")); + +Test.run([ + [ + "Core_IntTests.res", + 48, + 20, + 50 + ], + "range - start == end, step 0" +], Int.range(3, 3, { + step: 0 +}), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 50, + 13, + 52 + ], + "range + positive, increasing, step -1" +], Int.range(3, 6, { + step: -1 +}), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 56, + 13, + 51 + ], + "range + positive, decreasing, step 1" +], Int.range(6, 3, { + step: 1 +}), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 62, + 13, + 52 + ], + "range + positive, decreasing, step -2" +], Int.range(6, 3, { + step: -2 +}), eq, [ + 6, + 4 +]); + +Test.run([ + [ + "Core_IntTests.res", + 68, + 13, + 52 + ], + "range + positive, increasing, step -2" +], Int.range(6, 2, { + step: -2 +}), eq, [ + 6, + 4 +]); + +Test.run([ + [ + "Core_IntTests.res", + 74, + 13, + 52 + ], + "range + positive, increasing, step -2" +], Int.range(6, 1, { + step: -2 +}), eq, [ + 6, + 4, + 2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 80, + 13, + 52 + ], + "range + negative, decreasing, step -2" +], Int.range(-3, -6, { + step: -2 +}), eq, [ + -3, + -5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 86, + 13, + 62 + ], + "range - positive, increasing, step 2, inclusive" +], Int.range(3, 6, { + step: 2, + inclusive: true +}), eq, [ + 3, + 5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 92, + 13, + 62 + ], + "range + positive, increasing, step 2, inclusive" +], Int.range(3, 7, { + step: 2, + inclusive: true +}), eq, [ + 3, + 5, + 7 +]); + +Test.run([ + [ + "Core_IntTests.res", + 98, + 13, + 62 + ], + "range + positive, increasing, step 2, inclusive" +], Int.range(3, 8, { + step: 2, + inclusive: true +}), eq, [ + 3, + 5, + 7 +]); + +Test.run([ + [ + "Core_IntTests.res", + 104, + 13, + 62 + ], + "range - negative, increasing, step 2, inclusive" +], Int.range(-6, -3, { + step: 2, + inclusive: true +}), eq, [ + -6, + -4 +]); + +Test.run([ + [ + "Core_IntTests.res", + 110, + 13, + 62 + ], + "range - positive, increasing, step 0, inclusive" +], $$catch(() => Int.range(3, 6, { + step: 0, + inclusive: true +})), eq, new RangeError("Incorrect range arguments")); + +Test.run([ + [ + "Core_IntTests.res", + 116, + 13, + 54 + ], + "range - start == end, step 0, inclusive" +], Int.range(3, 3, { + step: 0, + inclusive: true +}), eq, [3]); + +Test.run([ + [ + "Core_IntTests.res", + 122, + 13, + 63 + ], + "range + positive, increasing, step -1, inclusive" +], Int.range(3, 6, { + step: -1, + inclusive: true +}), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 128, + 13, + 62 + ], + "range + positive, decreasing, step 1, inclusive" +], Int.range(6, 3, { + step: 1, + inclusive: true +}), eq, []); + +Test.run([ + [ + "Core_IntTests.res", + 134, + 13, + 63 + ], + "range + positive, decreasing, step -2, inclusive" +], Int.range(6, 3, { + step: -2, + inclusive: true +}), eq, [ + 6, + 4 +]); + +Test.run([ + [ + "Core_IntTests.res", + 140, + 13, + 63 + ], + "range + positive, increasing, step -2, inclusive" +], Int.range(6, 2, { + step: -2, + inclusive: true +}), eq, [ + 6, + 4, + 2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 146, + 13, + 63 + ], + "range + positive, increasing, step -2, inclusive" +], Int.range(6, 1, { + step: -2, + inclusive: true +}), eq, [ + 6, + 4, + 2 +]); + +Test.run([ + [ + "Core_IntTests.res", + 152, + 13, + 63 + ], + "range + negative, decreasing, step -2, inclusive" +], Int.range(-3, -6, { + step: -2, + inclusive: true +}), eq, [ + -3, + -5 +]); + +Test.run([ + [ + "Core_IntTests.res", + 158, + 20, + 27 + ], + "clamp" +], Int.clamp(undefined, undefined, 42), eq, 42); + +Test.run([ + [ + "Core_IntTests.res", + 159, + 20, + 35 + ], + "clamp - < min" +], Int.clamp(50, undefined, 42), eq, 50); + +Test.run([ + [ + "Core_IntTests.res", + 160, + 20, + 35 + ], + "clamp - > min" +], Int.clamp(40, undefined, 42), eq, 42); + +Test.run([ + [ + "Core_IntTests.res", + 161, + 20, + 35 + ], + "clamp - < max" +], Int.clamp(undefined, 50, 42), eq, 42); + +Test.run([ + [ + "Core_IntTests.res", + 162, + 20, + 35 + ], + "clamp - > max" +], Int.clamp(undefined, 40, 42), eq, 40); + +Test.run([ + [ + "Core_IntTests.res", + 163, + 20, + 42 + ], + "clamp - < min, < max" +], Int.clamp(50, 60, 42), eq, 50); + +Test.run([ + [ + "Core_IntTests.res", + 164, + 20, + 42 + ], + "clamp - < min, > max" +], Int.clamp(50, 40, 42), eq, 50); + +Test.run([ + [ + "Core_IntTests.res", + 165, + 20, + 42 + ], + "clamp - > min, < max" +], Int.clamp(40, 60, 42), eq, 42); + +Test.run([ + [ + "Core_IntTests.res", + 166, + 20, + 42 + ], + "clamp - > min, > max" +], Int.clamp(40, 40, 42), eq, 40); + +Test.run([ + [ + "Core_IntTests.res", + 168, + 20, + 44 + ], + "Int.equal optimization" +], false, eq, false); + +export { + eq, + $$catch, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_IntTests.res b/tests/tests/src/core/Core_IntTests.res new file mode 100644 index 0000000000..b9d88125a3 --- /dev/null +++ b/tests/tests/src/core/Core_IntTests.res @@ -0,0 +1,168 @@ +let eq = (a, b) => a == b + +let catch = f => + try { + let _ = f() + failwith("no exception raised") + } catch { + | Exn.Error(err) => err + } + +Test.run(__POS_OF__("range - positive, increasing"), Int.range(3, 6), eq, [3, 4, 5]) +Test.run(__POS_OF__("range - negative, increasing"), Int.range(-3, -1), eq, [-3, -2]) +Test.run(__POS_OF__("range - cross-zero, incresing"), Int.range(-1, 2), eq, [-1, 0, 1]) +Test.run(__POS_OF__("range - start == end"), Int.range(3, 3), eq, []) +Test.run(__POS_OF__("range - positive, decreasing"), Int.range(3, 1), eq, [3, 2]) +Test.run(__POS_OF__("range - negative, decreasing"), Int.range(-1, -3), eq, [-1, -2]) + +Test.run( + __POS_OF__("range - positive, increasing, step 2"), + Int.range(3, 6, ~options={step: 2}), + eq, + [3, 5], +) +Test.run( + __POS_OF__("range + positive, increasing, step 2"), + Int.range(3, 7, ~options={step: 2}), + eq, + [3, 5], +) +Test.run( + __POS_OF__("range + positive, increasing, step 2"), + Int.range(3, 8, ~options={step: 2}), + eq, + [3, 5, 7], +) +Test.run( + __POS_OF__("range - negative, increasing, step 2"), + Int.range(-6, -3, ~options={step: 2}), + eq, + [-6, -4], +) +Test.run( + __POS_OF__("range - positive, increasing, step 0"), + catch(() => Int.range(3, 6, ~options={step: 0})), + eq, + Error.RangeError.make("Incorrect range arguments"), +) +Test.run(__POS_OF__("range - start == end, step 0"), Int.range(3, 3, ~options={step: 0}), eq, []) +Test.run( + __POS_OF__("range + positive, increasing, step -1"), + Int.range(3, 6, ~options={step: -1}), + eq, + [], +) +Test.run( + __POS_OF__("range + positive, decreasing, step 1"), + Int.range(6, 3, ~options={step: 1}), + eq, + [], +) +Test.run( + __POS_OF__("range + positive, decreasing, step -2"), + Int.range(6, 3, ~options={step: -2}), + eq, + [6, 4], +) +Test.run( + __POS_OF__("range + positive, increasing, step -2"), + Int.range(6, 2, ~options={step: -2}), + eq, + [6, 4], +) +Test.run( + __POS_OF__("range + positive, increasing, step -2"), + Int.range(6, 1, ~options={step: -2}), + eq, + [6, 4, 2], +) +Test.run( + __POS_OF__("range + negative, decreasing, step -2"), + Int.range(-3, -6, ~options={step: -2}), + eq, + [-3, -5], +) +Test.run( + __POS_OF__("range - positive, increasing, step 2, inclusive"), + Int.range(3, 6, ~options={step: 2, inclusive: true}), + eq, + [3, 5], +) +Test.run( + __POS_OF__("range + positive, increasing, step 2, inclusive"), + Int.range(3, 7, ~options={step: 2, inclusive: true}), + eq, + [3, 5, 7], +) +Test.run( + __POS_OF__("range + positive, increasing, step 2, inclusive"), + Int.range(3, 8, ~options={step: 2, inclusive: true}), + eq, + [3, 5, 7], +) +Test.run( + __POS_OF__("range - negative, increasing, step 2, inclusive"), + Int.range(-6, -3, ~options={step: 2, inclusive: true}), + eq, + [-6, -4], +) +Test.run( + __POS_OF__("range - positive, increasing, step 0, inclusive"), + catch(() => Int.range(3, 6, ~options={step: 0, inclusive: true})), + eq, + Error.RangeError.make("Incorrect range arguments"), +) +Test.run( + __POS_OF__("range - start == end, step 0, inclusive"), + Int.range(3, 3, ~options={step: 0, inclusive: true}), + eq, + [3], +) +Test.run( + __POS_OF__("range + positive, increasing, step -1, inclusive"), + Int.range(3, 6, ~options={step: -1, inclusive: true}), + eq, + [], +) +Test.run( + __POS_OF__("range + positive, decreasing, step 1, inclusive"), + Int.range(6, 3, ~options={step: 1, inclusive: true}), + eq, + [], +) +Test.run( + __POS_OF__("range + positive, decreasing, step -2, inclusive"), + Int.range(6, 3, ~options={step: -2, inclusive: true}), + eq, + [6, 4], +) +Test.run( + __POS_OF__("range + positive, increasing, step -2, inclusive"), + Int.range(6, 2, ~options={step: -2, inclusive: true}), + eq, + [6, 4, 2], +) +Test.run( + __POS_OF__("range + positive, increasing, step -2, inclusive"), + Int.range(6, 1, ~options={step: -2, inclusive: true}), + eq, + [6, 4, 2], +) +Test.run( + __POS_OF__("range + negative, decreasing, step -2, inclusive"), + Int.range(-3, -6, ~options={step: -2, inclusive: true}), + eq, + [-3, -5], +) + +Test.run(__POS_OF__("clamp"), Int.clamp(42), eq, 42) +Test.run(__POS_OF__("clamp - < min"), Int.clamp(~min=50, 42), eq, 50) +Test.run(__POS_OF__("clamp - > min"), Int.clamp(~min=40, 42), eq, 42) +Test.run(__POS_OF__("clamp - < max"), Int.clamp(~max=50, 42), eq, 42) +Test.run(__POS_OF__("clamp - > max"), Int.clamp(~max=40, 42), eq, 40) +Test.run(__POS_OF__("clamp - < min, < max"), Int.clamp(~min=50, ~max=60, 42), eq, 50) +Test.run(__POS_OF__("clamp - < min, > max"), Int.clamp(~min=50, ~max=40, 42), eq, 50) // min wins +Test.run(__POS_OF__("clamp - > min, < max"), Int.clamp(~min=40, ~max=60, 42), eq, 42) +Test.run(__POS_OF__("clamp - > min, > max"), Int.clamp(~min=40, ~max=40, 42), eq, 40) + +Test.run(__POS_OF__("Int.equal optimization"), Int.equal(1, 3), eq, false) diff --git a/tests/tests/src/core/Core_IteratorTests.mjs b/tests/tests/src/core/Core_IteratorTests.mjs new file mode 100644 index 0000000000..f79c9cefe1 --- /dev/null +++ b/tests/tests/src/core/Core_IteratorTests.mjs @@ -0,0 +1,113 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as $$Iterator from "rescript/lib/es6/Iterator.js"; +import * as $$AsyncIterator from "rescript/lib/es6/AsyncIterator.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +let iterator = ((() => { + var array1 = ['a', 'b', 'c']; + var iterator1 = array1[Symbol.iterator](); + return iterator1 + })()); + +let syncResult = { + contents: undefined +}; + +$$Iterator.forEach(iterator, v => { + if (v === "b") { + syncResult.contents = "b"; + return; + } + +}); + +Test.run([ + [ + "Core_IteratorTests.res", + 19, + 20, + 34 + ], + "Sync forEach" +], syncResult.contents, eq, "b"); + +let asyncIterator = ((() => { + var map1 = new Map(); + + map1.set('first', '1'); + map1.set('second', '2'); + + var iterator1 = map1[Symbol.iterator](); + return iterator1; + })()); + +let asyncResult = { + contents: undefined +}; + +await $$AsyncIterator.forEach(asyncIterator, v => { + if (v !== undefined && v[0] === "second") { + asyncResult.contents = "second"; + return; + } + +}); + +Test.run([ + [ + "Core_IteratorTests.res", + 42, + 20, + 35 + ], + "Async forEach" +], asyncResult.contents, eq, "second"); + +let asyncResult$1 = { + contents: undefined +}; + +let count = { + contents: 0 +}; + +let asyncIterator$1 = $$AsyncIterator.make(async () => { + let currentCount = count.contents; + count.contents = currentCount + 1 | 0; + if (currentCount === 3) { + return $$AsyncIterator.done(currentCount); + } else { + return $$AsyncIterator.value(currentCount); + } +}); + +await $$AsyncIterator.forEach(asyncIterator$1, v => { + if (v === 3) { + asyncResult$1.contents = "done"; + } else { + console.log("next.."); + } +}); + +Test.run([ + [ + "Core_IteratorTests.res", + 67, + 20, + 54 + ], + "Creating your own async iterator" +], asyncResult$1.contents, eq, "done"); + +export { + eq, + iterator, + syncResult, + asyncResult, + asyncIterator$1 as asyncIterator, +} +/* iterator Not a pure module */ diff --git a/tests/tests/src/core/Core_IteratorTests.res b/tests/tests/src/core/Core_IteratorTests.res new file mode 100644 index 0000000000..5c5d302297 --- /dev/null +++ b/tests/tests/src/core/Core_IteratorTests.res @@ -0,0 +1,67 @@ +let eq = (a, b) => a == b + +let iterator: Iterator.t = %raw(` + (() => { + var array1 = ['a', 'b', 'c']; + var iterator1 = array1[Symbol.iterator](); + return iterator1 + })() +`) + +let syncResult = ref(None) + +iterator->Iterator.forEach(v => { + if v === Some("b") { + syncResult.contents = Some("b") + } +}) + +Test.run(__POS_OF__("Sync forEach"), syncResult.contents, eq, Some("b")) + +let asyncIterator: AsyncIterator.t<(string, string)> = %raw(` + (() => { + var map1 = new Map(); + + map1.set('first', '1'); + map1.set('second', '2'); + + var iterator1 = map1[Symbol.iterator](); + return iterator1; + })() +`) + +let asyncResult = ref(None) + +await asyncIterator->AsyncIterator.forEach(v => { + switch v { + | Some(("second", _value)) => asyncResult.contents = Some("second") + | _ => () + } +}) + +Test.run(__POS_OF__("Async forEach"), asyncResult.contents, eq, Some("second")) + +%%private( + let asyncResult = ref(None) + let count = ref(0) +) + +let asyncIterator = AsyncIterator.make(async () => { + let currentCount = count.contents + count := currentCount + 1 + + if currentCount === 3 { + AsyncIterator.done(~finalValue=currentCount) + } else { + AsyncIterator.value(currentCount) + } +}) + +await asyncIterator->AsyncIterator.forEach(v => { + switch v { + | Some(3) => asyncResult.contents = Some("done") + | _ => Console.log("next..") + } +}) + +Test.run(__POS_OF__("Creating your own async iterator"), asyncResult.contents, eq, Some("done")) diff --git a/tests/tests/src/core/Core_JsonTests.mjs b/tests/tests/src/core/Core_JsonTests.mjs new file mode 100644 index 0000000000..8898a2d2b0 --- /dev/null +++ b/tests/tests/src/core/Core_JsonTests.mjs @@ -0,0 +1,45 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; + +function decodeJsonTest() { + let json = {"someProp":{"otherProp": null, "thirdProp": [true, false]}}; + let decodedCorrectly; + if (!Array.isArray(json) && (json === null || typeof json !== "object") && typeof json !== "number" && typeof json !== "string" && typeof json !== "boolean" || !(typeof json === "object" && !Array.isArray(json))) { + decodedCorrectly = false; + } else { + let match = json["someProp"]; + if (match !== undefined && !(!Array.isArray(match) && (match === null || typeof match !== "object") && typeof match !== "number" && typeof match !== "string" && typeof match !== "boolean" || !(typeof match === "object" && !Array.isArray(match)))) { + let match$1 = match["thirdProp"]; + if (match$1 !== undefined && !(!Array.isArray(match$1) && (match$1 === null || typeof match$1 !== "object") && typeof match$1 !== "number" && typeof match$1 !== "string" && typeof match$1 !== "boolean" || !(Array.isArray(match$1) && match$1.length === 2))) { + let match$2 = match$1[0]; + if (!Array.isArray(match$2) && (match$2 === null || typeof match$2 !== "object") && typeof match$2 !== "number" && typeof match$2 !== "string" && typeof match$2 !== "boolean" || !(typeof match$2 === "boolean" && match$2)) { + decodedCorrectly = false; + } else { + let match$3 = match$1[1]; + decodedCorrectly = !Array.isArray(match$3) && (match$3 === null || typeof match$3 !== "object") && typeof match$3 !== "number" && typeof match$3 !== "string" && typeof match$3 !== "boolean" || !(typeof match$3 === "boolean" && !match$3) ? false : true; + } + } else { + decodedCorrectly = false; + } + } else { + decodedCorrectly = false; + } + } + Test.run([ + [ + "Core_JsonTests.res", + 17, + 22, + 55 + ], + "Should decode JSON successfully" + ], decodedCorrectly, (prim0, prim1) => prim0 === prim1, true); +} + +decodeJsonTest(); + +export { + decodeJsonTest, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_JsonTests.res b/tests/tests/src/core/Core_JsonTests.res new file mode 100644 index 0000000000..09d6d85661 --- /dev/null +++ b/tests/tests/src/core/Core_JsonTests.res @@ -0,0 +1,20 @@ +let decodeJsonTest = () => { + let json: JSON.t = %raw(`{"someProp":{"otherProp": null, "thirdProp": [true, false]}}`) + + let decodedCorrectly = switch json { + | Object(dict) => + switch dict->Dict.get("someProp") { + | Some(Object(dict)) => + switch dict->Dict.get("thirdProp") { + | Some(Array([Boolean(true), Boolean(false)])) => true + | _ => false + } + | _ => false + } + | _ => false + } + + Test.run(__POS_OF__("Should decode JSON successfully"), decodedCorrectly, \"==", true) +} + +decodeJsonTest() diff --git a/tests/tests/src/core/Core_NullableTests.mjs b/tests/tests/src/core/Core_NullableTests.mjs new file mode 100644 index 0000000000..072aa64f28 --- /dev/null +++ b/tests/tests/src/core/Core_NullableTests.mjs @@ -0,0 +1,49 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; + +function shouldHandleNullableValues() { + let tNull = null; + let tUndefined = undefined; + let tValue = "hello"; + let tmp; + tmp = (tNull === null || tNull === undefined) && tNull === null ? true : false; + Test.run([ + [ + "Core_NullableTests.res", + 7, + 15, + 35 + ], + "Should handle null" + ], tmp, (prim0, prim1) => prim0 === prim1, true); + let tmp$1; + tmp$1 = (tUndefined === null || tUndefined === undefined) && tUndefined !== null ? true : false; + Test.run([ + [ + "Core_NullableTests.res", + 17, + 15, + 40 + ], + "Should handle undefined" + ], tmp$1, (prim0, prim1) => prim0 === prim1, true); + let tmp$2; + tmp$2 = tValue === null || tValue === undefined || tValue !== "hello" ? false : true; + Test.run([ + [ + "Core_NullableTests.res", + 27, + 15, + 36 + ], + "Should handle value" + ], tmp$2, (prim0, prim1) => prim0 === prim1, true); +} + +shouldHandleNullableValues(); + +export { + shouldHandleNullableValues, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_NullableTests.res b/tests/tests/src/core/Core_NullableTests.res new file mode 100644 index 0000000000..3fefa8dfff --- /dev/null +++ b/tests/tests/src/core/Core_NullableTests.res @@ -0,0 +1,37 @@ +let shouldHandleNullableValues = () => { + let tNull: Nullable.t = %raw("null") + let tUndefined: Nullable.t = %raw("undefined") + let tValue: Nullable.t = %raw(`"hello"`) + + Test.run( + __POS_OF__("Should handle null"), + switch tNull { + | Null => true + | Value(_) | Undefined => false + }, + \"==", + true, + ) + + Test.run( + __POS_OF__("Should handle undefined"), + switch tUndefined { + | Undefined => true + | Value(_) | Null => false + }, + \"==", + true, + ) + + Test.run( + __POS_OF__("Should handle value"), + switch tValue { + | Value("hello") => true + | _ => false + }, + \"==", + true, + ) +} + +shouldHandleNullableValues() diff --git a/tests/tests/src/core/Core_ObjectTests.mjs b/tests/tests/src/core/Core_ObjectTests.mjs new file mode 100644 index 0000000000..78b3c4fb32 --- /dev/null +++ b/tests/tests/src/core/Core_ObjectTests.mjs @@ -0,0 +1,609 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Option from "rescript/lib/es6/Option.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_ObjectTests.res", + 10, + 20, + 30 + ], + "is: ints" +], Object.is(25, 25), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 12, + 20, + 33 + ], + "is: strings" +], Object.is("abc", "abc"), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 13, + 20, + 33 + ], + "is: strings" +], Object.is("abc", "ABC"), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 15, + 20, + 44 + ], + "is: null and undefined" +], Object.is(null, undefined), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 16, + 20, + 44 + ], + "is: null and undefined" +], Object.is(undefined, undefined), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 17, + 20, + 44 + ], + "is: null and undefined" +], Object.is(null, null), eq, true); + +let nums = [ + 1, + 2, + 3 +]; + +Test.run([ + [ + "Core_ObjectTests.res", + 20, + 20, + 32 + ], + "is: arrays" +], Object.is([ + 1, + 2, + 3 +], [ + 1, + 2, + 3 +]), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 21, + 20, + 32 + ], + "is: arrays" +], Object.is(nums, nums), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 22, + 20, + 32 + ], + "is: arrays" +], Primitive_object.equal([ + 1, + 2, + 3 +], [ + 1, + 2, + 3 +]), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 23, + 20, + 32 + ], + "is: arrays" +], [ + 1, + 2, + 3 +] === [ + 1, + 2, + 3 +], eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 25, + 20, + 30 + ], + "is: list" +], Object.is({ + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}, { + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 26, + 20, + 30 + ], + "is: list" +], Primitive_object.equal({ + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}, { + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 27, + 20, + 30 + ], + "is: list" +], ({ + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}) === ({ + hd: 1, + tl: { + hd: 2, + tl: { + hd: 3, + tl: /* [] */0 + } + } +}), eq, false); + +let d = new Date(2000, 1); + +Test.run([ + [ + "Core_ObjectTests.res", + 31, + 13, + 23 + ], + "is: date" +], Object.is(new Date(2000, 1), new Date(2000, 1)), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 36, + 20, + 30 + ], + "is: date" +], Object.is(d, d), eq, true); + +let x = { + a: 1 +}; + +Test.run([ + [ + "Core_ObjectTests.res", + 39, + 20, + 33 + ], + "is: objects" +], Object.is(x, x), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 40, + 20, + 33 + ], + "is: objects" +], Object.is({ + a: 1 +}, { + a: 1 +}), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 41, + 20, + 33 + ], + "is: objects" +], Object.is({}, {}), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 42, + 20, + 45 + ], + "is: === and == operator" +], x === x, eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 43, + 20, + 45 + ], + "is: === and == operator" +], Primitive_object.equal(x, x), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 44, + 20, + 45 + ], + "is: === and == operator" +], Primitive_object.equal({ + a: 1 +}, { + a: 1 +}), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 46, + 20, + 31 + ], + "is: zeros" +], Object.is(0, 0), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 47, + 20, + 31 + ], + "is: zeros" +], Object.is(-0.0, -0.0), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 48, + 20, + 31 + ], + "is: zeros" +], Object.is(0.0, -0.0), eq, false); + +function mkBig(s) { + return BigInt(s); +} + +Test.run([ + [ + "Core_ObjectTests.res", + 51, + 20, + 32 + ], + "is: bigint" +], Object.is(BigInt("123456789"), BigInt("123456789")), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 52, + 20, + 32 + ], + "is: bigint" +], Object.is(BigInt("123489"), BigInt("123456789")), eq, false); + +Test.run([ + [ + "Core_ObjectTests.res", + 53, + 20, + 32 + ], + "is: bigint" +], Object.is(BigInt("000000000"), BigInt("0")), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 54, + 20, + 32 + ], + "is: bigint" +], BigInt("123") === BigInt("123"), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 55, + 20, + 32 + ], + "is: bigint" +], BigInt("123") === BigInt("123"), eq, true); + +Test.run([ + [ + "Core_ObjectTests.res", + 60, + 13, + 50 + ], + "assign copies from source to target" +], Object.assign({ + a: 1, + b: 2 +}, { + b: 3, + c: 0 +}), eq, { + a: 1, + b: 3, + c: 0 +}); + +function assignOverwritesTarget(title, source) { + let sourceObj = { + a: source + }; + Test.run([ + [ + "Core_ObjectTests.res", + 68, + 22, + 39 + ], + "assign " + title + ], Object.assign({ + a: 1 + }, sourceObj), eq, sourceObj); + Test.run([ + [ + "Core_ObjectTests.res", + 69, + 22, + 39 + ], + "assign " + title + ], Object.assign({ + a: undefined + }, sourceObj), eq, sourceObj); + Test.run([ + [ + "Core_ObjectTests.res", + 70, + 22, + 39 + ], + "assign " + title + ], Object.assign({ + a: null + }, sourceObj), eq, sourceObj); +} + +assignOverwritesTarget("when source is undefined", undefined); + +assignOverwritesTarget("when source is null", null); + +assignOverwritesTarget("when source is a number", 1); + +assignOverwritesTarget("when source is a string", "abc"); + +function runGetTest(i) { + Test.run([ + [ + "Core_ObjectTests.res", + 88, + 22, + 46 + ], + "Object.get: " + i.title + ], i.get(i.source()), eq, i.expected); +} + +runGetTest({ + title: "prop exists, return Some", + source: () => ({ + a: 1 + }), + get: __x => __x["a"], + expected: 1 +}); + +runGetTest({ + title: "prop NOT exist, return None", + source: () => ({ + a: 1 + }), + get: i => i["banana"], + expected: undefined +}); + +runGetTest({ + title: "prop like toString, return Some", + source: () => ({ + a: 1 + }), + get: i => Option.isSome(i["toString"]), + expected: true +}); + +runGetTest({ + title: "prop exist but explicitly undefined, return None", + source: () => ({ + a: undefined + }), + get: i => i["a"], + expected: undefined +}); + +runGetTest({ + title: "prop exist but explicitly null, return None", + source: () => ({ + a: null + }), + get: i => i["a"], + expected: null +}); + +runGetTest({ + title: "prop exists and is an array, can get it", + source: () => ({ + a: [ + 1, + 2, + 3 + ] + }), + get: i => Option.getOr(Option.map(i["a"], i => i.concat([ + 4, + 5 + ])), []), + expected: [ + 1, + 2, + 3, + 4, + 5 + ] +}); + +function getSymbolTestWhenExists() { + let obj = {}; + let fruit = Symbol("fruit"); + obj[fruit] = "banana"; + let retrieved = obj[fruit]; + Test.run([ + [ + "Core_ObjectTests.res", + 148, + 15, + 63 + ], + "Object.getSymbol when exists return it as Some" + ], retrieved, eq, "banana"); +} + +getSymbolTestWhenExists(); + +Test.run([ + [ + "Core_ObjectTests.res", + 157, + 13, + 65 + ], + "Object.getSymbol when not exists return it as None" +], ({})[Symbol("fruit")], eq, undefined); + +Test.run([ + [ + "Core_ObjectTests.res", + 166, + 13, + 46 + ], + "Object.create clones properties" +], Object.create({ + a: 1 + })["a"], eq, 1); + +Test.run([ + [ + "Core_ObjectTests.res", + 173, + 13, + 46 + ], + "Object.create clones properties" +], Object.create({ + a: 1 + })["b"], eq, undefined); + +export { + eq, + nums, + d, + x, + mkBig, + assignOverwritesTarget, + runGetTest, + getSymbolTestWhenExists, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_ObjectTests.res b/tests/tests/src/core/Core_ObjectTests.res new file mode 100644 index 0000000000..ee139d805e --- /dev/null +++ b/tests/tests/src/core/Core_ObjectTests.res @@ -0,0 +1,177 @@ +let eq = (a, b) => a == b + +// ===== is ===== + +// == Removed when argument types were changed to be the same == +// Test.run(__POS_OF__("is: different types"), Object.is("abc", false), eq, false) +// Test.run(__POS_OF__("is: null and undefined"), Object.is(null, None), eq, false) +// Test.run(__POS_OF__("is: undefined and None"), Object.is(undefined, None), eq, true) + +Test.run(__POS_OF__("is: ints"), Object.is(25, 25), eq, true) + +Test.run(__POS_OF__("is: strings"), Object.is("abc", "abc"), eq, true) +Test.run(__POS_OF__("is: strings"), Object.is("abc", "ABC"), eq, false) + +Test.run(__POS_OF__("is: null and undefined"), Object.is(null, undefined), eq, false) +Test.run(__POS_OF__("is: null and undefined"), Object.is(undefined, undefined), eq, true) +Test.run(__POS_OF__("is: null and undefined"), Object.is(null, null), eq, true) + +let nums = [1, 2, 3] +Test.run(__POS_OF__("is: arrays"), Object.is([1, 2, 3], [1, 2, 3]), eq, false) +Test.run(__POS_OF__("is: arrays"), Object.is(nums, nums), eq, true) +Test.run(__POS_OF__("is: arrays"), [1, 2, 3] == [1, 2, 3], eq, true) +Test.run(__POS_OF__("is: arrays"), [1, 2, 3] === [1, 2, 3], eq, false) + +Test.run(__POS_OF__("is: list"), Object.is(list{1, 2, 3}, list{1, 2, 3}), eq, false) +Test.run(__POS_OF__("is: list"), list{1, 2, 3} == list{1, 2, 3}, eq, true) +Test.run(__POS_OF__("is: list"), list{1, 2, 3} === list{1, 2, 3}, eq, false) + +let d = Date.makeWithYM(~year=2000, ~month=1) +Test.run( + __POS_OF__("is: date"), + Object.is(Date.makeWithYM(~year=2000, ~month=1), Date.makeWithYM(~year=2000, ~month=1)), + eq, + false, +) +Test.run(__POS_OF__("is: date"), Object.is(d, d), eq, true) + +let x = {"a": 1} +Test.run(__POS_OF__("is: objects"), Object.is(x, x), eq, true) +Test.run(__POS_OF__("is: objects"), Object.is({"a": 1}, {"a": 1}), eq, false) +Test.run(__POS_OF__("is: objects"), Object.is(Object.make(), Object.make()), eq, false) // hmm... +Test.run(__POS_OF__("is: === and == operator"), x === x, eq, true) +Test.run(__POS_OF__("is: === and == operator"), x == x, eq, true) +Test.run(__POS_OF__("is: === and == operator"), {"a": 1} == {"a": 1}, eq, true) + +Test.run(__POS_OF__("is: zeros"), Object.is(-0, -0), eq, true) +Test.run(__POS_OF__("is: zeros"), Object.is(-0.0, -0.0), eq, true) +Test.run(__POS_OF__("is: zeros"), Object.is(0.0, -0.0), eq, false) + +let mkBig = s => BigInt.fromString(s) +Test.run(__POS_OF__("is: bigint"), Object.is(mkBig("123456789"), mkBig("123456789")), eq, true) +Test.run(__POS_OF__("is: bigint"), Object.is(mkBig("123489"), mkBig("123456789")), eq, false) +Test.run(__POS_OF__("is: bigint"), Object.is(mkBig("000000000"), mkBig("0")), eq, true) +Test.run(__POS_OF__("is: bigint"), mkBig("123") == mkBig("123"), eq, true) +Test.run(__POS_OF__("is: bigint"), mkBig("123") === mkBig("123"), eq, true) + +// ====== assign ====== + +Test.run( + __POS_OF__("assign copies from source to target"), + Object.assign({"a": 1, "b": 2}, {"b": 3, "c": 0}), + eq, + {"a": 1, "b": 3, "c": 0}, +) + +let assignOverwritesTarget = (~title, ~source) => { + let sourceObj = {"a": source} + Test.run(__POS_OF__(`assign ${title}`), Object.assign({"a": 1}, sourceObj), eq, sourceObj) + Test.run(__POS_OF__(`assign ${title}`), Object.assign({"a": undefined}, sourceObj), eq, sourceObj) + Test.run(__POS_OF__(`assign ${title}`), Object.assign({"a": null}, sourceObj), eq, sourceObj) +} + +assignOverwritesTarget(~title="when source is undefined", ~source=undefined) +assignOverwritesTarget(~title="when source is null", ~source=null) +assignOverwritesTarget(~title="when source is a number", ~source=1) +assignOverwritesTarget(~title="when source is a string", ~source="abc") + +// ===== get ===== + +type getTestData<'obj, 'res, 'expected> = { + title: string, + source: unit => 'obj, + get: 'obj => 'res, + expected: 'expected, +} + +let runGetTest = i => + Test.run(__POS_OF__(`Object.get: ${i.title}`), i.source()->i.get, eq, i.expected) + +{ + title: "prop exists, return Some", + source: () => {"a": 1}, + get: Object.get(_, "a"), + expected: Some(1), +}->runGetTest + +{ + title: "prop NOT exist, return None", + source: () => {"a": 1}, + get: i => i->Object.get("banana"), + expected: None, +}->runGetTest + +{ + title: "prop like toString, return Some", + source: () => {"a": 1}, + get: i => i->Object.get("toString")->Option.isSome, + expected: true, +}->runGetTest + +{ + title: "prop exist but explicitly undefined, return None", + source: () => {"a": undefined}, + get: i => i->Object.get("a"), + expected: None, +}->runGetTest + +{ + title: "prop exist but explicitly null, return None", + source: () => {"a": null}, + get: i => i->Object.get("a"), + expected: Some(null), +}->runGetTest + +{ + title: "prop exists and is an array, can get it", + source: () => {"a": [1, 2, 3]}, + get: i => i->Object.get("a")->Option.map(i => i->Array.concat([4, 5]))->Option.getOr([]), + expected: [1, 2, 3, 4, 5], +}->runGetTest + +// This throws an exception +// { +// title: "prop exists but casted wrong on get", +// source: () => {"a": 34}, +// get: i => i->Object.get("a")->Option.map(i => i->Array.concat([4, 5]))->Option.getWithDefault([]), +// expected: [], +// }->runGetTest + +// ===== getSymbol ===== + +let getSymbolTestWhenExists = () => { + let obj = Object.make() + let fruit = Symbol.make("fruit") + obj->Object.setSymbol(fruit, "banana") + let retrieved = obj->Object.getSymbol(fruit) + Test.run( + __POS_OF__(`Object.getSymbol when exists return it as Some`), + retrieved, + eq, + Some("banana"), + ) +} +getSymbolTestWhenExists() + +Test.run( + __POS_OF__(`Object.getSymbol when not exists return it as None`), + Object.make()->Object.getSymbol(Symbol.make("fruit")), + eq, + None, +) + +// ===== create ===== + +Test.run( + __POS_OF__(`Object.create clones properties`), + {"a": 1}->Object.create->Object.get("a"), + eq, + Some(1), +) + +Test.run( + __POS_OF__(`Object.create clones properties`), + {"a": 1}->Object.create->Object.get("b"), + eq, + None, +) diff --git a/tests/tests/src/core/Core_PromiseTest.mjs b/tests/tests/src/core/Core_PromiseTest.mjs new file mode 100644 index 0000000000..f054f6895c --- /dev/null +++ b/tests/tests/src/core/Core_PromiseTest.mjs @@ -0,0 +1,684 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Exn from "rescript/lib/es6/Exn.js"; +import * as Test from "./Test.mjs"; +import * as $$Promise from "rescript/lib/es6/Promise.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; +import * as Primitive_exceptions from "rescript/lib/es6/Primitive_exceptions.js"; + +let TestError = /* @__PURE__ */Primitive_exceptions.create("Core_PromiseTest.TestError"); + +let fail = Exn.raiseError; + +let equal = Primitive_object.equal; + +function resolveTest() { + Promise.resolve("test").then(str => { + Test.run([ + [ + "Core_PromiseTest.res", + 17, + 26, + 47 + ], + "Should resolve test" + ], str, equal, "test"); + return Promise.resolve(); + }); +} + +function runTests() { + resolveTest(); +} + +let Creation = { + resolveTest: resolveTest, + runTests: runTests +}; + +function testThen() { + return Promise.resolve(1).then(first => Promise.resolve(first + 1 | 0)).then(value => { + Test.run([ + [ + "Core_PromiseTest.res", + 39, + 26, + 39 + ], + "Should be 2" + ], value, equal, 2); + return Promise.resolve(); + }); +} + +function testInvalidThen() { + return Promise.resolve(1).then(first => Promise.resolve(Promise.resolve(first + 1 | 0))).then(p => { + let isPromise = typeof p === "object"; + Test.run([ + [ + "Core_PromiseTest.res", + 54, + 26, + 51 + ], + "Should not be a promise" + ], isPromise, equal, false); + return Promise.resolve(); + }); +} + +function testThenResolve() { + return Promise.resolve(1).then(num => num + 1 | 0).then(ret => Test.run([ + [ + "Core_PromiseTest.res", + 67, + 26, + 39 + ], + "Should be 2" + ], ret, equal, 2)); +} + +function testInvalidThenResolve() { + return Promise.resolve(1).then(num => Promise.resolve(num)).then(p => { + let isPromise = typeof p === "object"; + Test.run([ + [ + "Core_PromiseTest.res", + 81, + 26, + 51 + ], + "Should not be a promise" + ], isPromise, equal, false); + return Promise.resolve(); + }); +} + +function runTests$1() { + testThen(); + testInvalidThen(); + testThenResolve(); + testInvalidThenResolve(); +} + +let ThenChaining = { + testThen: testThen, + testInvalidThen: testInvalidThen, + testThenResolve: testThenResolve, + testInvalidThenResolve: testInvalidThenResolve, + runTests: runTests$1 +}; + +function testExnRejection() { + $$Promise.$$catch(Promise.reject({ + RE_EXN_ID: TestError, + _1: "oops" + }), e => { + Test.run([ + [ + "Core_PromiseTest.res", + 103, + 26, + 30 + ], + "Expect rejection to contain a TestError" + ], e, equal, { + RE_EXN_ID: TestError, + _1: "oops" + }); + return Promise.resolve(); + }); +} + +function runTests$2() { + testExnRejection(); +} + +let Rejection = { + testExnRejection: testExnRejection, + runTests: runTests$2 +}; + +let asyncParseFail = (function() { + return new Promise((resolve) => { + var result = JSON.parse("{.."); + return resolve(result); + }) + }); + +function testExternalPromiseThrow() { + return $$Promise.$$catch(asyncParseFail().then(param => Promise.resolve()), e => { + let success = e.RE_EXN_ID === Exn.$$Error ? Primitive_object.equal(e._1.name, "SyntaxError") : false; + Test.run([ + [ + "Core_PromiseTest.res", + 137, + 26, + 76 + ], + "Should be a parser error with Unexpected token ." + ], success, equal, true); + return Promise.resolve(); + }); +} + +function testExnThrow() { + return $$Promise.$$catch(Promise.resolve().then(() => { + throw { + RE_EXN_ID: TestError, + _1: "Thrown exn", + Error: new Error() + }; + }), e => { + let isTestErr = e.RE_EXN_ID === TestError && e._1 === "Thrown exn" ? true : false; + Test.run([ + [ + "Core_PromiseTest.res", + 156, + 26, + 49 + ], + "Should be a TestError" + ], isTestErr, equal, true); + return Promise.resolve(); + }); +} + +function testRaiseErrorThrow() { + return $$Promise.$$catch(Promise.resolve().then(() => Exn.raiseError("Some JS error")), e => { + let isTestErr = e.RE_EXN_ID === Exn.$$Error ? Primitive_object.equal(e._1.message, "Some JS error") : false; + Test.run([ + [ + "Core_PromiseTest.res", + 179, + 26, + 51 + ], + "Should be some JS error" + ], isTestErr, equal, true); + return Promise.resolve(); + }); +} + +function thenAfterCatch() { + return $$Promise.$$catch(Promise.resolve().then(() => Promise.reject({ + RE_EXN_ID: TestError, + _1: "some rejected value" + })), e => { + let tmp; + tmp = e.RE_EXN_ID === TestError && e._1 === "some rejected value" ? "success" : "not a test error"; + return Promise.resolve(tmp); + }).then(msg => { + Test.run([ + [ + "Core_PromiseTest.res", + 202, + 26, + 45 + ], + "Should be success" + ], msg, equal, "success"); + return Promise.resolve(); + }); +} + +function testCatchFinally() { + let wasCalled = { + contents: false + }; + $$Promise.$$catch(Promise.resolve(5).then(param => Promise.reject({ + RE_EXN_ID: TestError, + _1: "test" + })).then(v => Promise.resolve(v)), param => Promise.resolve()).finally(() => { + wasCalled.contents = true; + }).then(v => { + Test.run([ + [ + "Core_PromiseTest.res", + 224, + 26, + 48 + ], + "value should be unit" + ], v, equal, undefined); + Test.run([ + [ + "Core_PromiseTest.res", + 225, + 26, + 59 + ], + "finally should have been called" + ], wasCalled.contents, equal, true); + return Promise.resolve(); + }); +} + +function testResolveFinally() { + let wasCalled = { + contents: false + }; + Promise.resolve(5).then(v => Promise.resolve(v + 5 | 0)).finally(() => { + wasCalled.contents = true; + }).then(v => { + Test.run([ + [ + "Core_PromiseTest.res", + 242, + 26, + 45 + ], + "value should be 5" + ], v, equal, 10); + Test.run([ + [ + "Core_PromiseTest.res", + 243, + 26, + 59 + ], + "finally should have been called" + ], wasCalled.contents, equal, true); + return Promise.resolve(); + }); +} + +function runTests$3() { + testExternalPromiseThrow(); + testExnThrow(); + testRaiseErrorThrow(); + thenAfterCatch(); + testCatchFinally(); + testResolveFinally(); +} + +let Catching = { + asyncParseFail: asyncParseFail, + testExternalPromiseThrow: testExternalPromiseThrow, + testExnThrow: testExnThrow, + testRaiseErrorThrow: testRaiseErrorThrow, + thenAfterCatch: thenAfterCatch, + testCatchFinally: testCatchFinally, + testResolveFinally: testResolveFinally, + runTests: runTests$3 +}; + +function testParallel() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1000, "is Anna"); + let p2 = delayedMsg(500, "myName"); + let p3 = delayedMsg(100, "Hi"); + return Promise.all([ + p1, + p2, + p3 + ]).then(arr => { + let exp = [ + [ + 3, + "is Anna" + ], + [ + 2, + "myName" + ], + [ + 1, + "Hi" + ] + ]; + Test.run([ + [ + "Core_PromiseTest.res", + 280, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, exp); + return Promise.resolve(); + }); +} + +function testRace() { + let racer = (ms, name) => new Promise((resolve, param) => { + setTimeout(() => resolve(name), ms); + }); + let promises = [ + racer(1000, "Turtle"), + racer(500, "Hare"), + racer(100, "Eagle") + ]; + return Promise.race(promises).then(winner => { + Test.run([ + [ + "Core_PromiseTest.res", + 299, + 26, + 44 + ], + "Eagle should win" + ], winner, equal, "Eagle"); + return Promise.resolve(); + }); +} + +function testParallel2() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1000, "is Anna"); + let p2 = delayedMsg(500, "myName"); + return Promise.all([ + p1, + p2 + ]).then(arr => { + Test.run([ + [ + "Core_PromiseTest.res", + 323, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, [ + [ + 2, + "is Anna" + ], + [ + 1, + "myName" + ] + ]); + return Promise.resolve(); + }); +} + +function testParallel3() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1000, "is Anna"); + let p2 = delayedMsg(500, "myName"); + let p3 = delayedMsg(100, "Hi"); + return Promise.all([ + p1, + p2, + p3 + ]).then(arr => { + Test.run([ + [ + "Core_PromiseTest.res", + 348, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, [ + [ + 3, + "is Anna" + ], + [ + 2, + "myName" + ], + [ + 1, + "Hi" + ] + ]); + return Promise.resolve(); + }); +} + +function testParallel4() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1500, "Anna"); + let p2 = delayedMsg(1000, "is"); + let p3 = delayedMsg(500, "my name"); + let p4 = delayedMsg(100, "Hi"); + return Promise.all([ + p1, + p2, + p3, + p4 + ]).then(arr => { + Test.run([ + [ + "Core_PromiseTest.res", + 374, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, [ + [ + 4, + "Anna" + ], + [ + 3, + "is" + ], + [ + 2, + "my name" + ], + [ + 1, + "Hi" + ] + ]); + return Promise.resolve(); + }); +} + +function testParallel5() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1500, "Anna"); + let p2 = delayedMsg(1000, "is"); + let p3 = delayedMsg(500, "name"); + let p4 = delayedMsg(100, "my"); + let p5 = delayedMsg(50, "Hi"); + return Promise.all([ + p1, + p2, + p3, + p4, + p5 + ]).then(arr => { + Test.run([ + [ + "Core_PromiseTest.res", + 401, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, [ + [ + 5, + "Anna" + ], + [ + 4, + "is" + ], + [ + 3, + "name" + ], + [ + 2, + "my" + ], + [ + 1, + "Hi" + ] + ]); + return Promise.resolve(); + }); +} + +function testParallel6() { + let place = { + contents: 0 + }; + let delayedMsg = (ms, msg) => new Promise((resolve, param) => { + setTimeout(() => { + place.contents = place.contents + 1 | 0; + resolve([ + place.contents, + msg + ]); + }, ms); + }); + let p1 = delayedMsg(1500, "Anna"); + let p2 = delayedMsg(1000, "is"); + let p3 = delayedMsg(500, "name"); + let p4 = delayedMsg(100, "my"); + let p5 = delayedMsg(50, ", "); + let p6 = delayedMsg(10, "Hi"); + return Promise.all([ + p1, + p2, + p3, + p4, + p5, + p6 + ]).then(arr => { + Test.run([ + [ + "Core_PromiseTest.res", + 429, + 26, + 55 + ], + "Should have correct placing" + ], arr, equal, [ + [ + 6, + "Anna" + ], + [ + 5, + "is" + ], + [ + 4, + "name" + ], + [ + 3, + "my" + ], + [ + 2, + ", " + ], + [ + 1, + "Hi" + ] + ]); + return Promise.resolve(); + }); +} + +function runTests$4() { + testParallel(); + testRace(); + testParallel2(); + testParallel3(); + testParallel4(); + testParallel5(); + testParallel6(); +} + +let Concurrently = { + testParallel: testParallel, + testRace: testRace, + testParallel2: testParallel2, + testParallel3: testParallel3, + testParallel4: testParallel4, + testParallel5: testParallel5, + testParallel6: testParallel6, + runTests: runTests$4 +}; + +resolveTest(); + +runTests$1(); + +testExnRejection(); + +runTests$3(); + +runTests$4(); + +export { + TestError, + fail, + equal, + Creation, + ThenChaining, + Rejection, + Catching, + Concurrently, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_PromiseTest.res b/tests/tests/src/core/Core_PromiseTest.res new file mode 100644 index 0000000000..6a5ad72b8c --- /dev/null +++ b/tests/tests/src/core/Core_PromiseTest.res @@ -0,0 +1,449 @@ +exception TestError(string) + +let fail = msg => { + Exn.raiseError(msg) +} + +let equal = (a, b) => { + a == b +} + +module Creation = { + let resolveTest = () => { + open Promise + + Promise.resolve("test") + ->then(str => { + Test.run(__POS_OF__("Should resolve test"), str, equal, "test") + resolve() + }) + ->ignore + } + + let runTests = () => { + resolveTest() + } +} + +module ThenChaining = { + // A promise should be able to return a nested + // Promise and also flatten it for another then call + // to the actual value + let testThen = () => { + open Promise + resolve(1) + ->then(first => { + resolve(first + 1) + }) + ->then(value => { + Test.run(__POS_OF__("Should be 2"), value, equal, 2) + resolve() + }) + } + + // It's not allowed to return a promise> value + // within a then. This operation will throw an error + let testInvalidThen = () => { + open Promise + resolve(1) + ->then(first => { + resolve(resolve(first + 1)) + }) + ->then(p => { + let isPromise = Type.typeof((p: promise<_>)) == #object + Test.run(__POS_OF__("Should not be a promise"), isPromise, equal, false) + resolve() + }) + } + + let testThenResolve = () => { + open Promise + + resolve(1) + ->thenResolve(num => { + num + 1 + }) + ->thenResolve(ret => { + Test.run(__POS_OF__("Should be 2"), ret, equal, 2) + }) + } + + let testInvalidThenResolve = () => { + open Promise + + resolve(1) + ->thenResolve(num => { + // This is against the law + resolve(num) + }) + ->then(p => { + let isPromise = Type.typeof((p: promise<_>)) == #object + Test.run(__POS_OF__("Should not be a promise"), isPromise, equal, false) + resolve() + }) + } + + let runTests = () => { + testThen()->ignore + testInvalidThen()->ignore + testThenResolve()->ignore + testInvalidThenResolve()->ignore + } +} + +module Rejection = { + // Should gracefully handle a exn passed via reject() + let testExnRejection = () => { + let cond = "Expect rejection to contain a TestError" + open Promise + + TestError("oops") + ->reject + ->catch(e => { + Test.run(__POS_OF__(cond), e, equal, TestError("oops")) + resolve() + }) + ->ignore + } + + let runTests = () => { + testExnRejection()->ignore + } +} + +module Catching = { + let asyncParseFail: unit => promise = %raw(` + function() { + return new Promise((resolve) => { + var result = JSON.parse("{.."); + return resolve(result); + }) + } + `) + + // Should correctly capture an JS error thrown within + // a Promise `then` function + let testExternalPromiseThrow = () => { + open Promise + + asyncParseFail() + ->then(_ => resolve()) // Since our asyncParse will fail anyways, we convert to promise for our catch later + ->catch(e => { + let success = switch e { + | Exn.Error(err) => Exn.name(err) == Some("SyntaxError") + | _ => false + } + + Test.run(__POS_OF__("Should be a parser error with Unexpected token ."), success, equal, true) + resolve() + }) + } + + // Should correctly capture an exn thrown in a Promise + // `then` function + let testExnThrow = () => { + open Promise + + resolve() + ->then(_ => { + raise(TestError("Thrown exn")) + }) + ->catch(e => { + let isTestErr = switch e { + | TestError("Thrown exn") => true + | _ => false + } + Test.run(__POS_OF__("Should be a TestError"), isTestErr, equal, true) + resolve() + }) + } + + // Should correctly capture a JS error raised with Exn.raiseError + // within a Promise then function + let testRaiseErrorThrow = () => { + open Promise + + let causeErr = () => { + Exn.raiseError("Some JS error") + } + + resolve() + ->then(_ => { + causeErr() + }) + ->catch(e => { + let isTestErr = switch e { + | Exn.Error(err) => Exn.message(err) == Some("Some JS error") + | _ => false + } + Test.run(__POS_OF__("Should be some JS error"), isTestErr, equal, true) + resolve() + }) + } + + // Should recover a rejection and use then to + // access the value + let thenAfterCatch = () => { + open Promise + resolve() + ->then(_ => { + // NOTE: if then is used, there will be an uncaught + // error + reject(TestError("some rejected value")) + }) + ->catch(e => { + let s = switch e { + | TestError("some rejected value") => "success" + | _ => "not a test error" + } + resolve(s) + }) + ->then(msg => { + Test.run(__POS_OF__("Should be success"), msg, equal, "success") + resolve() + }) + } + + let testCatchFinally = () => { + open Promise + let wasCalled = ref(false) + resolve(5) + ->then(_ => { + reject(TestError("test")) + }) + ->then(v => { + v->resolve + }) + ->catch(_ => { + resolve() + }) + ->finally(() => { + wasCalled := true + }) + ->then(v => { + Test.run(__POS_OF__("value should be unit"), v, equal, ()) + Test.run(__POS_OF__("finally should have been called"), wasCalled.contents, equal, true) + resolve() + }) + ->ignore + } + + let testResolveFinally = () => { + open Promise + let wasCalled = ref(false) + resolve(5) + ->then(v => { + resolve(v + 5) + }) + ->finally(() => { + wasCalled := true + }) + ->then(v => { + Test.run(__POS_OF__("value should be 5"), v, equal, 10) + Test.run(__POS_OF__("finally should have been called"), wasCalled.contents, equal, true) + resolve() + }) + ->ignore + } + + let runTests = () => { + testExternalPromiseThrow()->ignore + testExnThrow()->ignore + testRaiseErrorThrow()->ignore + thenAfterCatch()->ignore + testCatchFinally()->ignore + testResolveFinally()->ignore + } +} + +module Concurrently = { + let testParallel = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1000, "is Anna") + let p2 = delayedMsg(500, "myName") + let p3 = delayedMsg(100, "Hi") + + all([p1, p2, p3])->then(arr => { + let exp = [(3, "is Anna"), (2, "myName"), (1, "Hi")] + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let testRace = () => { + open Promise + + let racer = (ms, name) => { + Promise.make((resolve, _) => { + setTimeout(() => { + resolve(name) + }, ms)->ignore + }) + } + + let promises = [racer(1000, "Turtle"), racer(500, "Hare"), racer(100, "Eagle")] + + race(promises)->then(winner => { + Test.run(__POS_OF__("Eagle should win"), winner, equal, "Eagle") + resolve() + }) + } + + let testParallel2 = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1000, "is Anna") + let p2 = delayedMsg(500, "myName") + + all2((p1, p2))->then(arr => { + let exp = ((2, "is Anna"), (1, "myName")) + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let testParallel3 = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1000, "is Anna") + let p2 = delayedMsg(500, "myName") + let p3 = delayedMsg(100, "Hi") + + all3((p1, p2, p3))->then(arr => { + let exp = ((3, "is Anna"), (2, "myName"), (1, "Hi")) + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let testParallel4 = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1500, "Anna") + let p2 = delayedMsg(1000, "is") + let p3 = delayedMsg(500, "my name") + let p4 = delayedMsg(100, "Hi") + + all4((p1, p2, p3, p4))->then(arr => { + let exp = ((4, "Anna"), (3, "is"), (2, "my name"), (1, "Hi")) + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let testParallel5 = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1500, "Anna") + let p2 = delayedMsg(1000, "is") + let p3 = delayedMsg(500, "name") + let p4 = delayedMsg(100, "my") + let p5 = delayedMsg(50, "Hi") + + all5((p1, p2, p3, p4, p5))->then(arr => { + let exp = ((5, "Anna"), (4, "is"), (3, "name"), (2, "my"), (1, "Hi")) + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let testParallel6 = () => { + open Promise + + let place = ref(0) + + let delayedMsg = (ms, msg) => { + Promise.make((resolve, _) => { + setTimeout(() => { + place := place.contents + 1 + resolve((place.contents, msg)) + }, ms)->ignore + }) + } + + let p1 = delayedMsg(1500, "Anna") + let p2 = delayedMsg(1000, "is") + let p3 = delayedMsg(500, "name") + let p4 = delayedMsg(100, "my") + let p5 = delayedMsg(50, ", ") + let p6 = delayedMsg(10, "Hi") + + all6((p1, p2, p3, p4, p5, p6))->then(arr => { + let exp = ((6, "Anna"), (5, "is"), (4, "name"), (3, "my"), (2, ", "), (1, "Hi")) + Test.run(__POS_OF__("Should have correct placing"), arr, equal, exp) + resolve() + }) + } + + let runTests = () => { + testParallel()->ignore + testRace()->ignore + testParallel2()->ignore + testParallel3()->ignore + testParallel4()->ignore + testParallel5()->ignore + testParallel6()->ignore + } +} + +Creation.runTests() +ThenChaining.runTests() +Rejection.runTests() +Catching.runTests() +Concurrently.runTests() diff --git a/tests/tests/src/core/Core_ResultTests.mjs b/tests/tests/src/core/Core_ResultTests.mjs new file mode 100644 index 0000000000..1179e2210e --- /dev/null +++ b/tests/tests/src/core/Core_ResultTests.mjs @@ -0,0 +1,92 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Result from "rescript/lib/es6/Result.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +function forEachIfOkCallFunction() { + let called = { + contents: [] + }; + Result.forEach({ + TAG: "Ok", + _0: 3 + }, i => { + called.contents.push(i); + }); + Test.run([ + [ + "Core_ResultTests.res", + 10, + 22, + 72 + ], + "forEach: if ok, call function with ok value once" + ], called.contents, eq, [3]); +} + +forEachIfOkCallFunction(); + +function forEachIfErrorDoNotCallFunction() { + let called = { + contents: [] + }; + Result.forEach({ + TAG: "Error", + _0: 3 + }, i => { + called.contents.push(i); + }); + Test.run([ + [ + "Core_ResultTests.res", + 17, + 22, + 63 + ], + "forEach: if error, do not call function" + ], called.contents, eq, []); +} + +forEachIfErrorDoNotCallFunction(); + +Test.run([ + [ + "Core_ResultTests.res", + 25, + 20, + 48 + ], + "mapError: if ok, return it" +], Result.mapError({ + TAG: "Ok", + _0: 5 +}, i => Math.imul(i, 3)), eq, { + TAG: "Ok", + _0: 5 +}); + +Test.run([ + [ + "Core_ResultTests.res", + 28, + 13, + 42 + ], + "mapError: if error, apply f" +], Result.mapError({ + TAG: "Error", + _0: 5 +}, i => Math.imul(i, 3)), eq, { + TAG: "Error", + _0: 15 +}); + +export { + eq, + forEachIfOkCallFunction, + forEachIfErrorDoNotCallFunction, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_ResultTests.res b/tests/tests/src/core/Core_ResultTests.res new file mode 100644 index 0000000000..54395a5a3b --- /dev/null +++ b/tests/tests/src/core/Core_ResultTests.res @@ -0,0 +1,32 @@ +let eq = (a, b) => a == b + +// ======= +// forEach +// ======= + +let forEachIfOkCallFunction = () => { + let called = ref([]) + Ok(3)->Result.forEach(i => called.contents->Array.push(i)) + Test.run(__POS_OF__("forEach: if ok, call function with ok value once"), called.contents, eq, [3]) +} +forEachIfOkCallFunction() + +let forEachIfErrorDoNotCallFunction = () => { + let called = ref([]) + Error(3)->Result.forEach(i => called.contents->Array.push(i)) + Test.run(__POS_OF__("forEach: if error, do not call function"), called.contents, eq, []) +} +forEachIfErrorDoNotCallFunction() + +// ======== +// mapError +// ======== + +Test.run(__POS_OF__("mapError: if ok, return it"), Ok(5)->Result.mapError(i => i * 3), eq, Ok(5)) + +Test.run( + __POS_OF__("mapError: if error, apply f"), + Error(5)->Result.mapError(i => i * 3), + eq, + Error(15), +) diff --git a/tests/tests/src/core/Core_StringTests.mjs b/tests/tests/src/core/Core_StringTests.mjs new file mode 100644 index 0000000000..bbdcc0fa0b --- /dev/null +++ b/tests/tests/src/core/Core_StringTests.mjs @@ -0,0 +1,21 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_StringTests.res", + 3, + 20, + 47 + ], + "String.equal optimization" +], false, eq, false); + +export { + eq, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_StringTests.res b/tests/tests/src/core/Core_StringTests.res new file mode 100644 index 0000000000..ad1010a310 --- /dev/null +++ b/tests/tests/src/core/Core_StringTests.res @@ -0,0 +1,3 @@ +let eq = (a, b) => a == b + +Test.run(__POS_OF__("String.equal optimization"), String.equal("one", "three"), eq, false) diff --git a/tests/tests/src/core/Core_TempTests.mjs b/tests/tests/src/core/Core_TempTests.mjs new file mode 100644 index 0000000000..4478b1d59e --- /dev/null +++ b/tests/tests/src/core/Core_TempTests.mjs @@ -0,0 +1,363 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Int from "rescript/lib/es6/Int.js"; +import * as Dict from "rescript/lib/es6/Dict.js"; +import * as $$JSON from "rescript/lib/es6/JSON.js"; +import * as $$Array from "rescript/lib/es6/Array.js"; +import * as Float from "rescript/lib/es6/Float.js"; +import * as $$BigInt from "rescript/lib/es6/BigInt.js"; +import * as Option from "rescript/lib/es6/Option.js"; +import * as Core_IntlTests from "./intl/Core_IntlTests.mjs"; +import * as Primitive_bigint from "rescript/lib/es6/Primitive_bigint.js"; +import * as Primitive_option from "rescript/lib/es6/Primitive_option.js"; + +console.info(""); + +console.info("Array"); + +console.info("---"); + +let array = [ + 1, + 2, + 3, + 4 +]; + +console.info($$Array.reduce(array.map(x => (x << 1)), 0, (a, b) => a + b | 0)); + +console.info(typeof array); + +console.info(""); + +console.info("Date"); + +console.info("---"); + +let date = new Date(Date.UTC(2020, 11)); + +console.log(date.toUTCString()); + +console.info(""); + +console.info("Dict"); + +console.info("---"); + +let dict = {}; + +dict["foo"] = "bar"; + +let dict2 = Object.assign({}, dict); + +Dict.$$delete(dict2, "foo"); + +console.log(dict, dict2); + +console.info(""); + +console.info("Error"); + +console.info("---"); + +function f() { + let error = new Error("hello"); + let typeError = new TypeError("error"); + let g = () => { + throw error; + }; + let h = () => { + throw typeError; + }; + return [ + g, + h + ]; +} + +console.info(""); + +console.info("Float/Int"); + +console.info("---"); + +console.log((10.2).toFixed(2)); + +console.log((10).toFixed(2)); + +console.log(Int.fromString("0", undefined)); + +console.log(Float.fromString("0.1")); + +console.info(""); + +console.info("JSON"); + +console.info("---"); + +let json = JSON.parse("{\"foo\": \"bar\"}"); + +let json$1 = $$JSON.Classify.classify(json); + +let tmp; + +if (typeof json$1 !== "object" || json$1.TAG !== "Object") { + tmp = undefined; +} else { + let value = $$JSON.Classify.classify(json$1._0["foo"]); + tmp = typeof value !== "object" || value.TAG !== "String" ? undefined : value._0; +} + +console.log(tmp); + +console.info(""); + +console.info("Map"); + +console.info("---"); + +let map = new Map(); + +map.set(1, 1); + +map.set(2, 2); + +map.delete(1); + +console.log(map); + +console.info(""); + +console.info("Math"); + +console.info("---"); + +console.log(Math.ceil(Math.PI / 2.0)); + +console.info(""); + +console.info("BigInt"); + +console.info("---"); + +console.log(Primitive_bigint.div(BigInt(1), BigInt(12.0))); + +console.info(""); + +console.info("Object"); + +console.info("---"); + +let myObject = { + foo: "bar" +}; + +console.log(Object.create(myObject)); + +console.log(Object.create(myObject, { + foo: { + value: "bar" + } +})); + +console.log(Object.create(null)); + +console.log(Object.create(null, { + foo: { + value: "bar" + } +})); + +let copy = Object.assign({}, myObject); + +let withNewProp = Object.assign(copy, { + bar: "baz" +}); + +console.info(""); + +console.info("Promise"); + +console.info("---"); + +let promise = new Promise((resolve, _reject) => { + setTimeout(() => resolve(1), 100); +}); + +promise.then(x => Promise.resolve(x + 1 | 0)).then(x => Promise.resolve(x + 2 | 0)).then(x => { + console.log(x); + return Promise.resolve(); +}).finally(() => { + console.log("Promise finally"); +}); + +console.info(""); + +console.info("RegExp"); + +console.info("---"); + +let regex = new RegExp("hello(\\w+)"); + +let string = "helloworld"; + +console.log(regex.test(string)); + +let result = regex.exec(string); + +let result$1 = (result == null) ? undefined : Primitive_option.some(result); + +console.log(Option.map(result$1, prim => prim.input)); + +console.log(Option.map(result$1, prim => prim.index)); + +console.log(Option.map(result$1, prim => prim.slice(1))); + +console.info(""); + +console.info("Set"); + +console.info("---"); + +let set = new Set(); + +set.add(1); + +set.add(2); + +set.delete(2); + +console.log(set); + +console.info(""); + +console.info("String"); + +console.info("---"); + +let regexp = new RegExp("(hello )(world)"); + +console.log(" Hello world ".toLowerCase().trim().replace(regexp, (param, group1, group2, param$1, param$2) => group1 + group2.toUpperCase())); + +console.info(""); + +console.info("Symbol"); + +console.info("---"); + +let x = Symbol.for("Foo"); + +console.log(x); + +let array$1 = Array.from("foo"[Symbol.iterator]()); + +console.log(array$1); + +console.info(""); + +console.info("Global namespace"); + +console.info("---"); + +console.log("number"); + +let timeout = setTimeout(() => { + console.log("Hello!"); +}, 100); + +clearTimeout(timeout); + +if (globalThis.hello !== undefined) { + console.log(globalThis.hello.bar); + console.log("hello"); +} + +let z = 1.2 % 1.4; + +let intFromBigInt = $$BigInt.toInt(BigInt("10000000000")); + +console.log({ + bar: "1" +}); + +let Bugfix = {}; + +console.log(Int.fromString("1231231", undefined)); + +console.log(Int.fromString("12.22", undefined)); + +console.log(Int.fromString("99999999999999999", undefined)); + +console.log(Int.fromString("99999999999999999", undefined)); + +console.log(Int.fromString("010101", 2)); + +let _collator = Core_IntlTests._collator; + +let collator = Core_IntlTests.collator; + +let resolvedOptions = Core_IntlTests.resolvedOptions; + +let timeZone = Core_IntlTests.timeZone; + +let _locale = Core_IntlTests._locale; + +let locale = Core_IntlTests.locale; + +let currencyFormatter = Core_IntlTests.currencyFormatter; + +let roundingFormatter = Core_IntlTests.roundingFormatter; + +let groupingFormatter1 = Core_IntlTests.groupingFormatter1; + +let groupingFormatter2 = Core_IntlTests.groupingFormatter2; + +let sigFormatter = Core_IntlTests.sigFormatter; + +let options = Core_IntlTests.options; + +let _formatter = Core_IntlTests._formatter; + +let formatter = Core_IntlTests.formatter; + +let segments = Core_IntlTests.segments; + +export { + _collator, + collator, + resolvedOptions, + timeZone, + _locale, + locale, + currencyFormatter, + roundingFormatter, + groupingFormatter1, + groupingFormatter2, + sigFormatter, + options, + _formatter, + formatter, + segments, + date, + dict, + dict2, + f, + json, + map, + myObject, + copy, + withNewProp, + promise, + regex, + string, + result$1 as result, + set, + regexp, + x, + array$1 as array, + timeout, + z, + intFromBigInt, + Bugfix, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_TempTests.res b/tests/tests/src/core/Core_TempTests.res new file mode 100644 index 0000000000..a3fe866caa --- /dev/null +++ b/tests/tests/src/core/Core_TempTests.res @@ -0,0 +1,196 @@ +include Core_IntlTests + +Console.info("") +Console.info("Array") +Console.info("---") +let array = [1, 2, 3, 4] +Console.info(array->Array.map(x => x * 2)->Array.reduce(0, (a, b) => a + b)) +Console.info(typeof(array)) + +Console.info("") +Console.info("Date") +Console.info("---") +let date = Date.fromTime(Date.UTC.makeWithYM(~year=2020, ~month=11)) +Console.log(date->Date.toUTCString) + +Console.info("") +Console.info("Dict") +Console.info("---") +let dict = Dict.make() +dict->Dict.set("foo", "bar") +let dict2 = dict->Dict.copy +dict2->Dict.delete("foo") +Console.log2(dict, dict2) + +Console.info("") +Console.info("Error") +Console.info("---") +let f = () => { + let error = Error.make("hello") + let typeError = Error.TypeError.make("error") + let g = () => Error.raise(error) + let h = () => Error.raise(typeError) + (g, h) +} + +Console.info("") +Console.info("Float/Int") +Console.info("---") +Console.log(10.2->Float.toFixed(~digits=2)) +Console.log(10->Int.toFixed(~digits=2)) +Console.log("0"->Int.fromString) +Console.log("0.1"->Float.fromString) + +Console.info("") +Console.info("JSON") +Console.info("---") +let json = JSON.parseExn(`{"foo": "bar"}`) +Console.log( + switch JSON.Classify.classify(json) { + | Object(json) => + switch JSON.Classify.classify(json->Dict.get("foo")) { + | String(value) => Some(value) + | _ => None + } + | _ => None + }, +) + +Console.info("") +Console.info("Map") +Console.info("---") +let map = Map.make() +let _ = map->Map.set(1, 1) +let _ = map->Map.set(2, 2) +let _ = map->Map.delete(1) +Console.log(map) + +Console.info("") +Console.info("Math") +Console.info("---") +Console.log(Math.ceil(Math.Constants.pi /. 2.0)) + +Console.info("") +Console.info("BigInt") +Console.info("---") + +@warning("-44") +Console.log({ + open BigInt + fromInt(1) / fromFloat(12.0) +}) + +Console.info("") +Console.info("Object") +Console.info("---") +let myObject = { + "foo": "bar", +} + +Console.log(Object.create(myObject)) +Console.log(Object.createWithProperties(myObject, {"foo": {"value": "bar"}})) +Console.log(Object.createWithNull()) +Console.log(Object.createWithNullAndProperties({"foo": {"value": "bar"}})) + +let copy = Object.copy(myObject) +let withNewProp = Object.assign(copy, {"bar": "baz"}) + +Console.info("") +Console.info("Promise") +Console.info("---") +let promise: promise = Promise.make((resolve, _reject) => { + let _ = setTimeout(() => { + resolve(1) + }, 100) +}) + +let _ = + promise + ->Promise.then(x => Promise.resolve(x + 1)) + ->Promise.then(x => Promise.resolve(x + 2)) + ->Promise.then(x => { + Console.log(x) + Promise.resolve() + }) + ->Promise.finally(() => { + Console.log("Promise finally") + }) + +Console.info("") +Console.info("RegExp") +Console.info("---") +let regex = RegExp.fromString("hello(\\w+)") +let string = "helloworld" +Console.log(regex->RegExp.test(string)) +let result = regex->RegExp.exec(string) +Console.log(result->Option.map(RegExp.Result.input)) +Console.log(result->Option.map(RegExp.Result.index)) +Console.log(result->Option.map(RegExp.Result.matches)) + +Console.info("") +Console.info("Set") +Console.info("---") +let set = Set.make() +set->Set.add(1) +set->Set.add(2) +let _ = set->Set.delete(2) +Console.log(set) + +Console.info("") +Console.info("String") +Console.info("---") +let regexp = RegExp.fromString("(hello )(world)") +Console.log( + " Hello world " + ->String.toLowerCase + ->String.trim + ->String.unsafeReplaceRegExpBy2(regexp, ( + ~match as _, + ~group1, + ~group2, + ~offset as _, + ~input as _, + ) => { + group1 ++ group2->String.toUpperCase + }), +) + +Console.info("") +Console.info("Symbol") +Console.info("---") +let x = Symbol.getFor("Foo") +Console.log(x) +let array: array = String.getSymbolUnsafe("foo", Symbol.iterator)()->Iterator.toArray +Console.log(array) + +Console.info("") +Console.info("Global namespace") +Console.info("---") + +Console.log(typeof(1)) + +let timeout = setTimeout(() => { + Console.log("Hello!") +}, 100) + +clearTimeout(timeout) + +if globalThis["hello"] !== undefined { + Console.log(globalThis["hello"]["bar"]) + Console.log("hello") +} + +let z = Float.mod(1.2, 1.4) + +let intFromBigInt = BigInt.fromString("10000000000")->BigInt.toInt + +module Bugfix = { + @obj external foo: (~bar: string=?, unit) => _ = "" + Console.log(foo(~bar="1", ())) +} + +Console.log(Int.fromString("1231231")) +Console.log(Int.fromString("12.22")) +Console.log(Int.fromString("99999999999999999")) +Console.log(Int.fromString("99999999999999999")) +Console.log(Int.fromString(~radix=2, "010101")) diff --git a/tests/tests/src/core/Core_TestSuite.mjs b/tests/tests/src/core/Core_TestSuite.mjs new file mode 100644 index 0000000000..5cdea30649 --- /dev/null +++ b/tests/tests/src/core/Core_TestSuite.mjs @@ -0,0 +1,121 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Core_IntTests from "./Core_IntTests.mjs"; +import * as Core_DictTests from "./Core_DictTests.mjs"; +import * as Core_JsonTests from "./Core_JsonTests.mjs"; +import * as Core_TestTests from "./Core_TestTests.mjs"; +import * as Core_ArrayTests from "./Core_ArrayTests.mjs"; +import * as Core_ErrorTests from "./Core_ErrorTests.mjs"; +import * as Core_FloatTests from "./Core_FloatTests.mjs"; +import * as Core_ObjectTests from "./Core_ObjectTests.mjs"; +import * as Core_PromiseTest from "./Core_PromiseTest.mjs"; +import * as Core_ResultTests from "./Core_ResultTests.mjs"; +import * as Core_IteratorTests from "./Core_IteratorTests.mjs"; +import * as Core_NullableTests from "./Core_NullableTests.mjs"; +import * as Core_TypedArrayTests from "./Core_TypedArrayTests.mjs"; + +let bign = Core_TestTests.bign; + +let TestError = Core_PromiseTest.TestError; + +let fail = Core_PromiseTest.fail; + +let equal = Core_PromiseTest.equal; + +let Creation = Core_PromiseTest.Creation; + +let ThenChaining = Core_PromiseTest.ThenChaining; + +let Rejection = Core_PromiseTest.Rejection; + +let Catching = Core_PromiseTest.Catching; + +let Concurrently = Core_PromiseTest.Concurrently; + +let panicTest = Core_ErrorTests.panicTest; + +let $$catch = Core_IntTests.$$catch; + +let nums = Core_ObjectTests.nums; + +let d = Core_ObjectTests.d; + +let x = Core_ObjectTests.x; + +let mkBig = Core_ObjectTests.mkBig; + +let assignOverwritesTarget = Core_ObjectTests.assignOverwritesTarget; + +let runGetTest = Core_ObjectTests.runGetTest; + +let getSymbolTestWhenExists = Core_ObjectTests.getSymbolTestWhenExists; + +let forEachIfOkCallFunction = Core_ResultTests.forEachIfOkCallFunction; + +let forEachIfErrorDoNotCallFunction = Core_ResultTests.forEachIfErrorDoNotCallFunction; + +let num1 = Core_TypedArrayTests.num1; + +let num2 = Core_TypedArrayTests.num2; + +let num3 = Core_TypedArrayTests.num3; + +let assertTrue = Core_TypedArrayTests.assertTrue; + +let assertWillThrow = Core_TypedArrayTests.assertWillThrow; + +let areSame = Core_TypedArrayTests.areSame; + +let o = Core_TypedArrayTests.o; + +let decodeJsonTest = Core_JsonTests.decodeJsonTest; + +let shouldHandleNullableValues = Core_NullableTests.shouldHandleNullableValues; + +let eq = Core_IteratorTests.eq; + +let iterator = Core_IteratorTests.iterator; + +let syncResult = Core_IteratorTests.syncResult; + +let asyncResult = Core_IteratorTests.asyncResult; + +let asyncIterator = Core_IteratorTests.asyncIterator; + +export { + bign, + TestError, + fail, + equal, + Creation, + ThenChaining, + Rejection, + Catching, + Concurrently, + panicTest, + $$catch, + nums, + d, + x, + mkBig, + assignOverwritesTarget, + runGetTest, + getSymbolTestWhenExists, + forEachIfOkCallFunction, + forEachIfErrorDoNotCallFunction, + num1, + num2, + num3, + assertTrue, + assertWillThrow, + areSame, + o, + decodeJsonTest, + shouldHandleNullableValues, + eq, + iterator, + syncResult, + asyncResult, + asyncIterator, +} +/* Core_IntTests Not a pure module */ diff --git a/tests/tests/src/core/Core_TestSuite.res b/tests/tests/src/core/Core_TestSuite.res new file mode 100644 index 0000000000..e048a3bd56 --- /dev/null +++ b/tests/tests/src/core/Core_TestSuite.res @@ -0,0 +1,13 @@ +include Core_TestTests +include Core_PromiseTest +include Core_ErrorTests +include Core_ArrayTests +include Core_IntTests +include Core_ObjectTests +include Core_ResultTests +include Core_TypedArrayTests +include Core_FloatTests +include Core_JsonTests +include Core_NullableTests +include Core_DictTests +include Core_IteratorTests diff --git a/tests/tests/src/core/Core_TestTests.mjs b/tests/tests/src/core/Core_TestTests.mjs new file mode 100644 index 0000000000..f39a4dce04 --- /dev/null +++ b/tests/tests/src/core/Core_TestTests.mjs @@ -0,0 +1,188 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Pervasives from "rescript/lib/es6/Pervasives.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +let bign = BigInt(Number.MAX_VALUE); + +let bign$1 = bign + bign; + +Test.run([ + [ + "Core_TestTests.res", + 6, + 20, + 32 + ], + "print null" +], Test.print(null), eq, "null"); + +Test.run([ + [ + "Core_TestTests.res", + 7, + 20, + 37 + ], + "print undefined" +], Test.print(undefined), eq, "undefined"); + +Test.run([ + [ + "Core_TestTests.res", + 8, + 20, + 31 + ], + "print NaN" +], Test.print(Number.NaN), eq, "NaN"); + +Test.run([ + [ + "Core_TestTests.res", + 9, + 20, + 36 + ], + "print infinity" +], Test.print(Pervasives.infinity), eq, "Infinity"); + +Test.run([ + [ + "Core_TestTests.res", + 10, + 20, + 29 + ], + "print 0" +], Test.print(0), eq, "0"); + +Test.run([ + [ + "Core_TestTests.res", + 11, + 20, + 31 + ], + "print int" +], Test.print(42), eq, "42"); + +Test.run([ + [ + "Core_TestTests.res", + 12, + 20, + 33 + ], + "print float" +], Test.print(4.2), eq, "4.2"); + +Test.run([ + [ + "Core_TestTests.res", + 13, + 20, + 34 + ], + "print string" +], Test.print("foo"), eq, "\"foo\""); + +Test.run([ + [ + "Core_TestTests.res", + 14, + 20, + 32 + ], + "print bool" +], Test.print(true), eq, "true"); + +Test.run([ + [ + "Core_TestTests.res", + 15, + 20, + 34 + ], + "print object" +], Test.print({ + x: 42 +}), eq, "{ x: 42 }"); + +Test.run([ + [ + "Core_TestTests.res", + 16, + 20, + 33 + ], + "print array" +], Test.print([ + 1, + 2, + 3 +]), eq, "[ 1, 2, 3 ]"); + +Test.run([ + [ + "Core_TestTests.res", + 17, + 20, + 34 + ], + "print symbol" +], Test.print(Symbol("foo")), eq, "Symbol(foo)"); + +Test.run([ + [ + "Core_TestTests.res", + 18, + 20, + 36 + ], + "print function" +], Test.print(() => 42), eq, "() => 42"); + +Test.run([ + [ + "Core_TestTests.res", + 19, + 20, + 40 + ], + "print es6 function" +], Test.print((() => 42)), eq, "() => 42"); + +Test.run([ + [ + "Core_TestTests.res", + 21, + 13, + 27 + ], + "print bigint" +], Test.print(bign$1), eq, "359538626972463141629054847463408713596141135051689993197834953606314521560057077521179117265533756343080917907028764928468642653778928365536935093407075033972099821153102564152490980180778657888151737016910267884609166473806445896331617118664246696549595652408289446337476354361838599762500808052368249716736n"); + +Test.run([ + [ + "Core_TestTests.res", + 26, + 20, + 31 + ], + "print set" +], Test.print(new Set([ + 1, + 2, + 2, + 3 +])), eq, "Set(3) { 1, 2, 3 }"); + +export { + eq, + bign$1 as bign, +} +/* bign Not a pure module */ diff --git a/tests/tests/src/core/Core_TestTests.res b/tests/tests/src/core/Core_TestTests.res new file mode 100644 index 0000000000..f2f0dcad99 --- /dev/null +++ b/tests/tests/src/core/Core_TestTests.res @@ -0,0 +1,26 @@ +let eq = (a, b) => a == b + +let bign = BigInt.fromFloat(Float.Constants.maxValue) +let bign = BigInt.add(bign, bign) + +Test.run(__POS_OF__("print null"), Test.print(null), eq, "null") +Test.run(__POS_OF__("print undefined"), Test.print(undefined), eq, "undefined") +Test.run(__POS_OF__("print NaN"), Test.print(nan), eq, "NaN") +Test.run(__POS_OF__("print infinity"), Test.print(infinity), eq, "Infinity") +Test.run(__POS_OF__("print 0"), Test.print(0), eq, "0") +Test.run(__POS_OF__("print int"), Test.print(42), eq, "42") +Test.run(__POS_OF__("print float"), Test.print(4.2), eq, "4.2") +Test.run(__POS_OF__("print string"), Test.print("foo"), eq, `"foo"`) +Test.run(__POS_OF__("print bool"), Test.print(true), eq, "true") +Test.run(__POS_OF__("print object"), Test.print({"x": 42}), eq, `{ x: 42 }`) +Test.run(__POS_OF__("print array"), Test.print([1, 2, 3]), eq, "[ 1, 2, 3 ]") +Test.run(__POS_OF__("print symbol"), Test.print(Symbol.make("foo")), eq, "Symbol(foo)") +Test.run(__POS_OF__("print function"), Test.print(() => 42), eq, "() => 42") +Test.run(__POS_OF__("print es6 function"), Test.print(%raw("() => 42")), eq, "() => 42") +Test.run( + __POS_OF__("print bigint"), + Test.print(bign), + eq, + "359538626972463141629054847463408713596141135051689993197834953606314521560057077521179117265533756343080917907028764928468642653778928365536935093407075033972099821153102564152490980180778657888151737016910267884609166473806445896331617118664246696549595652408289446337476354361838599762500808052368249716736n", +) +Test.run(__POS_OF__("print set"), Test.print(Set.fromArray([1, 2, 2, 3])), eq, "Set(3) { 1, 2, 3 }") diff --git a/tests/tests/src/core/Core_TypedArrayTests.mjs b/tests/tests/src/core/Core_TypedArrayTests.mjs new file mode 100644 index 0000000000..fd7fce21da --- /dev/null +++ b/tests/tests/src/core/Core_TypedArrayTests.mjs @@ -0,0 +1,101 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Test from "./Test.mjs"; +import * as Option from "rescript/lib/es6/Option.js"; +import * as Primitive_object from "rescript/lib/es6/Primitive_object.js"; + +let eq = Primitive_object.equal; + +Test.run([ + [ + "Core_TypedArrayTests.res", + 5, + 20, + 44 + ], + "bytes per element is 8" +], BigInt64Array.BYTES_PER_ELEMENT, eq, 8); + +let num1 = BigInt("123456789"); + +let num2 = BigInt("987654321"); + +let num3 = BigInt("555555555"); + +function assertTrue(message, predicate) { + try { + if (predicate()) { + return; + } + throw new Error(message); + } catch (exn) { + throw new Error(message); + } +} + +function assertWillThrow(message, f) { + let didThrow = false; + try { + f(); + } catch (exn) { + didThrow = true; + } + if (didThrow !== false) { + return; + } + throw new Error(message); +} + +function areSame(x, y) { + return x.toString() === y.toString(); +} + +assertTrue("fromArray", () => areSame(Option.getExn(new BigInt64Array([ + num1, + num2 + ])[1], undefined), num2)); + +assertTrue("fromBuffer", () => { + let x = new BigInt64Array(new ArrayBuffer(16)); + x[1] = num2; + return areSame(Option.getExn(x[1], undefined), num2); +}); + +assertWillThrow("fromBuffer when too short can throw when used", () => { + let x = new BigInt64Array(new ArrayBuffer(1)); + x[0] = num1; + areSame(Option.getExn(x[0], undefined), num1); +}); + +assertTrue("fromBufferWithRange", () => { + let x = new BigInt64Array(new ArrayBuffer(16), 0, 1); + x[0] = num1; + return areSame(Option.getExn(x[0], undefined), num1); +}); + +assertWillThrow("fromBufferWithRange is unsafe, out of range", () => { + let x = new BigInt64Array(new ArrayBuffer(16), 13, 1); + x[0] = num1; + areSame(Option.getExn(x[0], undefined), num1); +}); + +assertTrue("fromLength is NOT in bytes", () => { + let x = new BigInt64Array(1); + return x.byteLength === 8; +}); + +function o(prim0, prim1) { + return BigInt64Array.from(prim0, prim1); +} + +export { + eq, + num1, + num2, + num3, + assertTrue, + assertWillThrow, + areSame, + o, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/Core_TypedArrayTests.res b/tests/tests/src/core/Core_TypedArrayTests.res new file mode 100644 index 0000000000..b0719a1f62 --- /dev/null +++ b/tests/tests/src/core/Core_TypedArrayTests.res @@ -0,0 +1,74 @@ +let eq = (a, b) => a == b + +// ===== BigInt64Array Tests ===== + +Test.run(__POS_OF__("bytes per element is 8"), BigInt64Array.Constants.bytesPerElement, eq, 8) + +let num1 = BigInt.fromString("123456789") +let num2 = BigInt.fromString("987654321") +let num3 = BigInt.fromString("555555555") + +let assertTrue = (message, predicate) => { + try { + if !predicate() { + message->Error.make->Error.raise + } + } catch { + | _ => message->Error.make->Error.raise + } +} + +let assertWillThrow = (message, f) => { + let didThrow = ref(false) + try { + f() + } catch { + | _ => didThrow := true + } + if didThrow.contents == false { + message->Error.make->Error.raise + } +} + +let areSame = (x: bigint, y: bigint) => BigInt.toString(x) == BigInt.toString(y) + +// What's going on here? +// assertTrue("big ints if different then not equal", () => num1 != num2) +// assertTrue("big ints if same then equal", () => num1 == num1) + +assertTrue("fromArray", () => + [num1, num2]->BigInt64Array.fromArray->TypedArray.get(1)->Option.getExn->areSame(num2) +) + +assertTrue("fromBuffer", () => { + let x = ArrayBuffer.make(16)->BigInt64Array.fromBuffer + x->TypedArray.set(1, num2) + x->TypedArray.get(1)->Option.getExn->areSame(num2) +}) + +assertWillThrow("fromBuffer when too short can throw when used", () => { + let x = ArrayBuffer.make(1)->BigInt64Array.fromBuffer + x->TypedArray.set(0, num1) + x->TypedArray.get(0)->Option.getExn->areSame(num1)->ignore +}) + +assertTrue("fromBufferWithRange", () => { + let x = ArrayBuffer.make(16)->BigInt64Array.fromBufferWithRange(~byteOffset=0, ~length=1) + x->TypedArray.set(0, num1) + x->TypedArray.get(0)->Option.getExn->areSame(num1) +}) + +// assertWillThrow("testing", () => {"a"->Error.make->Error.raise}) +// assertWillThrow("testing", () => {Console.log("f")}) + +assertWillThrow("fromBufferWithRange is unsafe, out of range", () => { + let x = ArrayBuffer.make(16)->BigInt64Array.fromBufferWithRange(~byteOffset=13, ~length=1) + x->TypedArray.set(0, num1) + x->TypedArray.get(0)->Option.getExn->areSame(num1)->ignore +}) + +assertTrue("fromLength is NOT in bytes", () => { + let x = BigInt64Array.fromLength(1) + TypedArray.byteLength(x) == 8 +}) +let o = BigInt64Array.fromArrayLikeOrIterableWithMap diff --git a/tests/tests/src/core/Test.mjs b/tests/tests/src/core/Test.mjs new file mode 100644 index 0000000000..c24abc1c99 --- /dev/null +++ b/tests/tests/src/core/Test.mjs @@ -0,0 +1,53 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Fs from "fs"; +import * as Path from "path"; +import * as Util from "util"; +import * as Option from "rescript/lib/es6/Option.js"; +import * as CodeFrame from "@babel/code-frame"; + +let dirname = (new URL('.', import.meta.url).pathname); + +function print(value) { + let match = typeof value; + if (match === "object" || match === "bigint") { + return Util.inspect(value); + } else if (match === "string") { + return Option.getExn(JSON.stringify(value), undefined); + } else { + return String(value); + } +} + +function run(loc, left, comparator, right) { + if (comparator(left, right)) { + return; + } + let match = loc[0]; + let line = match[1]; + let file = match[0]; + let fileContent = Fs.readFileSync(Path.join(dirname, file), { + encoding: "utf-8" + }); + let left$1 = print(left); + let right$1 = print(right); + let codeFrame = CodeFrame.codeFrameColumns(fileContent, { + start: { + line: line + } + }, { + highlightCode: true + }); + let errorMessage = "\n \u001b[31mTest Failure!\n \u001b[36m" + file + "\u001b[0m:\u001b[2m" + String(line) + "\n" + codeFrame + "\n \u001b[39mLeft: \u001b[31m" + left$1 + "\n \u001b[39mRight: \u001b[31m" + right$1 + "\u001b[0m\n"; + console.log(errorMessage); + let obj = {}; + Error.captureStackTrace(obj); + console.log(obj.stack.replace(/\n /g, "\n ").replace(/^Error\n/, "").replace(/^.+\n/, "").replace(/\n at .+\(node:internal.+\n?/g, "")); +} + +export { + dirname, + print, + run, +} +/* dirname Not a pure module */ diff --git a/tests/tests/src/core/Test.res b/tests/tests/src/core/Test.res new file mode 100644 index 0000000000..d62638c910 --- /dev/null +++ b/tests/tests/src/core/Test.res @@ -0,0 +1,50 @@ +// Test "framework" + +@scope("process") @val external exit: int => unit = "exit" +@scope("Error") @val external captureStackTrace: {..} => unit = "captureStackTrace" +@module("@babel/code-frame") @val +external codeFrameColumns: (string, {..}, {..}) => string = "codeFrameColumns" +@module("fs") @val external readFileSync: (string, {..}) => string = "readFileSync" +@module("path") @val external join: (string, string) => string = "join" + +let dirname = %raw("new URL('.', import.meta.url).pathname") + +@val @module("util") external inspect: _ => string = "inspect" +let print = value => + switch Type.typeof(value) { + | #string => JSON.stringifyAny(value)->Option.getExn // uses " instead of ' + | #object | #bigint => inspect(value) + | _ => String.make(value) + } + +let run = (loc, left, comparator, right) => { + if !comparator(left, right) { + let ((file, line, _, _), _) = loc + let fileContent = readFileSync(join(dirname, file), {"encoding": "utf-8"}) + let left = print(left) + let right = print(right) + let codeFrame = codeFrameColumns( + fileContent, + {"start": {"line": line}}, + {"highlightCode": true}, + ) + let errorMessage = ` + \u001b[31mTest Failure! + \u001b[36m${file}\u001b[0m:\u001b[2m${string_of_int(line)} +${codeFrame} + \u001b[39mLeft: \u001b[31m${left} + \u001b[39mRight: \u001b[31m${right}\u001b[0m +` + Console.log(errorMessage) + // API: https://nodejs.org/api/errors.html#errors_error_capturestacktrace_targetobject_constructoropt + let obj = Object.make() + captureStackTrace(obj) + // clean up stack trace! Stack format: https://nodejs.org/api/errors.html#errors_error_stack + obj["stack"] + ->String.replaceRegExp(/\n /g, "\n ") // indent 2 spaces instead of 4, to align with code frame + ->String.replaceRegExp(/^Error\n/, "") // first line is just the word "Error" + ->String.replaceRegExp(/^.+\n/, "") // second line (now first) is this Test module's own stack frame + ->String.replaceRegExp(/\n at .+\(node:internal.+\n?/g, "") // remove internal lines like " at ModuleJob.run (node:internal/modules/esm/module_job:193:25)" + ->Console.log + } +} diff --git a/tests/tests/src/core/intl/Core_IntlTests.mjs b/tests/tests/src/core/intl/Core_IntlTests.mjs new file mode 100644 index 0000000000..3929756a37 --- /dev/null +++ b/tests/tests/src/core/intl/Core_IntlTests.mjs @@ -0,0 +1,130 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Exn from "rescript/lib/es6/Exn.js"; +import * as $$Error from "rescript/lib/es6/Error.js"; +import * as Option from "rescript/lib/es6/Option.js"; +import * as Primitive_option from "rescript/lib/es6/Primitive_option.js"; +import * as Core_Intl_LocaleTest from "./Core_Intl_LocaleTest.mjs"; +import * as Primitive_exceptions from "rescript/lib/es6/Primitive_exceptions.js"; +import * as Core_Intl_CollatorTest from "./Core_Intl_CollatorTest.mjs"; +import * as Core_Intl_SegmenterTest from "./Core_Intl_SegmenterTest.mjs"; +import * as Core_Intl_ListFormatTest from "./Core_Intl_ListFormatTest.mjs"; +import * as Core_Intl_PluralRulesTest from "./Core_Intl_PluralRulesTest.mjs"; +import * as Core_Intl_NumberFormatTest from "./Core_Intl_NumberFormatTest.mjs"; +import * as Core_Intl_DateTimeFormatTest from "./Core_Intl_DateTimeFormatTest.mjs"; +import * as Core_Intl_RelativeTimeFormatTest from "./Core_Intl_RelativeTimeFormatTest.mjs"; + +console.log("---"); + +console.log("Intl"); + +console.log(Intl.getCanonicalLocales("EN-US")); + +console.log(Intl.getCanonicalLocales([ + "EN-US", + "Fr" +])); + +try { + console.log(Intl.getCanonicalLocales("bloop")); +} catch (raw_e) { + let e = Primitive_exceptions.internalToException(raw_e); + if (e.RE_EXN_ID === Exn.$$Error) { + console.error(e._1); + } else { + throw e; + } +} + +try { + console.log(Intl.supportedValuesOf("calendar")); + console.log(Intl.supportedValuesOf("collation")); + console.log(Intl.supportedValuesOf("currency")); + console.log(Intl.supportedValuesOf("numberingSystem")); + console.log(Intl.supportedValuesOf("timeZone")); + console.log(Intl.supportedValuesOf("unit")); +} catch (raw_e$1) { + let e$1 = Primitive_exceptions.internalToException(raw_e$1); + if (e$1.RE_EXN_ID === Exn.$$Error) { + console.error(e$1._1); + } else { + throw e$1; + } +} + +try { + Intl.supportedValuesOf("someInvalidKey"); + console.error("Shouldn't have been hit"); +} catch (raw_e$2) { + let e$2 = Primitive_exceptions.internalToException(raw_e$2); + if (e$2.RE_EXN_ID === Exn.$$Error) { + let e$3 = e$2._1; + let message = Option.map(e$3.message, prim => prim.toLowerCase()); + let exit = 0; + if (message === "invalid key : someinvalidkey") { + console.log("Caught expected error"); + } else { + exit = 1; + } + if (exit === 1) { + console.warn("Unexpected error message: \"" + message + "\""); + throw e$3; + } + + } else { + let e$4 = $$Error.fromException(e$2); + if (e$4 !== undefined) { + throw Primitive_option.valFromOption(e$4); + } + console.error("Unexpected error"); + } +} + +let _collator = Core_Intl_CollatorTest._collator; + +let collator = Core_Intl_CollatorTest.collator; + +let resolvedOptions = Core_Intl_DateTimeFormatTest.resolvedOptions; + +let timeZone = Core_Intl_DateTimeFormatTest.timeZone; + +let _locale = Core_Intl_LocaleTest._locale; + +let locale = Core_Intl_LocaleTest.locale; + +let currencyFormatter = Core_Intl_NumberFormatTest.currencyFormatter; + +let roundingFormatter = Core_Intl_NumberFormatTest.roundingFormatter; + +let groupingFormatter1 = Core_Intl_NumberFormatTest.groupingFormatter1; + +let groupingFormatter2 = Core_Intl_NumberFormatTest.groupingFormatter2; + +let sigFormatter = Core_Intl_NumberFormatTest.sigFormatter; + +let options = Core_Intl_NumberFormatTest.options; + +let _formatter = Core_Intl_SegmenterTest._formatter; + +let formatter = Core_Intl_SegmenterTest.formatter; + +let segments = Core_Intl_SegmenterTest.segments; + +export { + _collator, + collator, + resolvedOptions, + timeZone, + _locale, + locale, + currencyFormatter, + roundingFormatter, + groupingFormatter1, + groupingFormatter2, + sigFormatter, + options, + _formatter, + formatter, + segments, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_IntlTests.res b/tests/tests/src/core/intl/Core_IntlTests.res new file mode 100644 index 0000000000..7b1f45d75e --- /dev/null +++ b/tests/tests/src/core/intl/Core_IntlTests.res @@ -0,0 +1,51 @@ +include Core_Intl_CollatorTest +include Core_Intl_DateTimeFormatTest +include Core_Intl_ListFormatTest +include Core_Intl_LocaleTest +include Core_Intl_NumberFormatTest +include Core_Intl_PluralRulesTest +include Core_Intl_RelativeTimeFormatTest +include Core_Intl_SegmenterTest + +Console.log("---") +Console.log("Intl") + +Intl.getCanonicalLocalesExn("EN-US")->Console.log +Intl.getCanonicalLocalesManyExn(["EN-US", "Fr"])->Console.log + +try { + Intl.getCanonicalLocalesExn("bloop")->Console.log +} catch { +| Exn.Error(e) => Console.error(e) +} + +try { + Intl.supportedValuesOfExn("calendar")->Console.log + Intl.supportedValuesOfExn("collation")->Console.log + Intl.supportedValuesOfExn("currency")->Console.log + Intl.supportedValuesOfExn("numberingSystem")->Console.log + Intl.supportedValuesOfExn("timeZone")->Console.log + Intl.supportedValuesOfExn("unit")->Console.log +} catch { +| Exn.Error(e) => Console.error(e) +} + +try { + Intl.supportedValuesOfExn("someInvalidKey")->ignore + + Console.error("Shouldn't have been hit") +} catch { +| Exn.Error(e) => + switch Error.message(e)->Option.map(String.toLowerCase) { + | Some("invalid key : someinvalidkey") => Console.log("Caught expected error") + | message => { + Console.warn(`Unexpected error message: "${message->Option.getUnsafe}"`) + Error.raise(e) + } + } +| e => + switch Error.fromException(e) { + | Some(e) => Error.raise(e) + | None => Console.error("Unexpected error") + } +} diff --git a/tests/tests/src/core/intl/Core_Intl_CollatorTest.mjs b/tests/tests/src/core/intl/Core_Intl_CollatorTest.mjs new file mode 100644 index 0000000000..b40e6e76ac --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_CollatorTest.mjs @@ -0,0 +1,46 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.Collator"); + +new Intl.Collator(); + +new Intl.Collator(["en-US"]); + +let _collator = new Intl.Collator([ + "en-US", + "en-GB" +]); + +let collator = new Intl.Collator(["en-US"], { + sensitivity: "base", + ignorePunctuation: true, + numeric: true, + caseFirst: "upper" +}); + +Intl.Collator.supportedLocalesOf([ + "en-US", + "en-GB" +]); + +Intl.Collator.supportedLocalesOf([ + "en-US", + "en-GB" +], { + localeMatcher: "lookup" +}); + +console.log(collator.resolvedOptions()); + +console.log(collator.compare("hi", "hï")); + +console.log(Intl.Collator.supportedLocalesOf(["hi"])); + +export { + _collator, + collator, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_CollatorTest.res b/tests/tests/src/core/intl/Core_Intl_CollatorTest.res new file mode 100644 index 0000000000..1983bdc416 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_CollatorTest.res @@ -0,0 +1,16 @@ +Console.log("---") +Console.log("Intl.Collator") + +let _collator = Intl.Collator.make() +let _collator = Intl.Collator.make(~locales=["en-US"]) +let _collator = Intl.Collator.make(~locales=["en-US", "en-GB"]) +let collator = Intl.Collator.make( + ~locales=["en-US"], + ~options={caseFirst: #upper, sensitivity: #base, ignorePunctuation: true, numeric: true}, +) +Intl.Collator.supportedLocalesOf(["en-US", "en-GB"])->ignore +Intl.Collator.supportedLocalesOf(["en-US", "en-GB"], ~options={localeMatcher: #lookup})->ignore + +collator->Intl.Collator.resolvedOptions->Console.log +collator->Intl.Collator.compare("hi", "hï")->Console.log +Intl.Collator.supportedLocalesOf(["hi"])->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.mjs b/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.mjs new file mode 100644 index 0000000000..c7008f5c7e --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.mjs @@ -0,0 +1,89 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.DateTimeFormat"); + +Intl.DateTimeFormat.supportedLocalesOf([ + "en-US", + "en-GB" +]); + +Intl.DateTimeFormat.supportedLocalesOf([ + "en-US", + "en-GB" +], { + localeMatcher: "lookup" +}); + +let formatter = new Intl.DateTimeFormat(undefined, { + dateStyle: "full", + timeStyle: "full" +}); + +console.log(formatter.format(new Date(Date.now()))); + +console.log(formatter.formatRange(new Date(2023, 1, 1), new Date(2023, 12, 31))); + +let options = { + timeZone: "UTC", + hour12: false, + hourCycle: "h24", + weekday: "narrow", + era: "narrow", + year: "2-digit", + month: "2-digit", + day: "2-digit", + hour: "2-digit", + minute: "2-digit", + second: "2-digit", + fractionalSecondDigits: 3, + timeZoneName: "longGeneric" +}; + +let formatter$1 = new Intl.DateTimeFormat(undefined, options); + +console.log(formatter$1.format(new Date(Date.now()))); + +let newrecord = {...options}; + +let formatter$2 = new Intl.DateTimeFormat(undefined, (newrecord.timeZoneName = "long", newrecord)); + +console.log(formatter$2.format(new Date(Date.now()))); + +let newrecord$1 = {...options}; + +let formatter$3 = new Intl.DateTimeFormat(undefined, (newrecord$1.timeZoneName = "longOffset", newrecord$1)); + +console.log(formatter$3.format(new Date(Date.now()))); + +let newrecord$2 = {...options}; + +let formatter$4 = new Intl.DateTimeFormat(undefined, (newrecord$2.timeZoneName = "short", newrecord$2)); + +console.log(formatter$4.format(new Date(Date.now()))); + +let newrecord$3 = {...options}; + +let formatter$5 = new Intl.DateTimeFormat(undefined, (newrecord$3.timeZoneName = "shortGeneric", newrecord$3)); + +console.log(formatter$5.format(new Date(Date.now()))); + +let newrecord$4 = {...options}; + +let formatter$6 = new Intl.DateTimeFormat(undefined, (newrecord$4.timeZoneName = "shortOffset", newrecord$4)); + +console.log(formatter$6.format(new Date(Date.now()))); + +let resolvedOptions = new Intl.DateTimeFormat().resolvedOptions(); + +let timeZone = resolvedOptions.timeZone; + +export { + options, + formatter$6 as formatter, + resolvedOptions, + timeZone, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.res b/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.res new file mode 100644 index 0000000000..b35ff9333d --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_DateTimeFormatTest.res @@ -0,0 +1,56 @@ +Console.log("---") +Console.log("Intl.DateTimeFormat") + +Intl.DateTimeFormat.supportedLocalesOf(["en-US", "en-GB"])->ignore +Intl.DateTimeFormat.supportedLocalesOf( + ["en-US", "en-GB"], + ~options={localeMatcher: #lookup}, +)->ignore + +let formatter = Intl.DateTimeFormat.make(~options={dateStyle: #full, timeStyle: #full}) + +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +Console.log( + formatter->Intl.DateTimeFormat.formatRange( + ~startDate=Date.makeWithYMD(~year=2023, ~date=1, ~month=1), + ~endDate=Date.makeWithYMD(~year=2023, ~date=31, ~month=12), + ), +) + +let options: Intl.DateTimeFormat.options = { + hour12: false, + hourCycle: #h24, + timeZone: "UTC", + weekday: #narrow, + era: #narrow, + year: #"2-digit", + month: #"2-digit", + day: #"2-digit", + hour: #"2-digit", + minute: #"2-digit", + second: #"2-digit", + fractionalSecondDigits: #3, + timeZoneName: #longGeneric, +} +let formatter = Intl.DateTimeFormat.make(~options) + +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let formatter = Intl.DateTimeFormat.make(~options={...options, timeZoneName: #long}) +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let formatter = Intl.DateTimeFormat.make(~options={...options, timeZoneName: #longOffset}) +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let formatter = Intl.DateTimeFormat.make(~options={...options, timeZoneName: #short}) +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let formatter = Intl.DateTimeFormat.make(~options={...options, timeZoneName: #shortGeneric}) +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let formatter = Intl.DateTimeFormat.make(~options={...options, timeZoneName: #shortOffset}) +Console.log(formatter->Intl.DateTimeFormat.format(Date.fromTime(Date.now()))) + +let resolvedOptions = Intl.DateTimeFormat.make()->Intl.DateTimeFormat.resolvedOptions +let {Intl.DateTimeFormat.timeZone: timeZone, _} = resolvedOptions diff --git a/tests/tests/src/core/intl/Core_Intl_ListFormatTest.mjs b/tests/tests/src/core/intl/Core_Intl_ListFormatTest.mjs new file mode 100644 index 0000000000..67d33f2b50 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_ListFormatTest.mjs @@ -0,0 +1,58 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.ListFormat"); + +new Intl.ListFormat(); + +new Intl.ListFormat([ + "en-US", + "en-GB" +]); + +let _formatter = new Intl.ListFormat([ + "en-US", + "en-GB" +], { + type: "conjunction", + style: "long" +}); + +Intl.ListFormat.supportedLocalesOf([ + "en-US", + "en-GB" +]); + +Intl.ListFormat.supportedLocalesOf([ + "en-US", + "en-GB" +], { + localeMatcher: "lookup" +}); + +let formatter = new Intl.ListFormat(undefined, { + type: "conjunction", + style: "long" +}); + +console.log(formatter.resolvedOptions()); + +console.log(formatter.format([ + "one", + "two", + "three" +])); + +console.log(formatter.formatToParts([ + "one", + "two", + "three" +])); + +export { + _formatter, + formatter, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_ListFormatTest.res b/tests/tests/src/core/intl/Core_Intl_ListFormatTest.res new file mode 100644 index 0000000000..d925c00ccd --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_ListFormatTest.res @@ -0,0 +1,17 @@ +Console.log("---") +Console.log("Intl.ListFormat") + +let _formatter = Intl.ListFormat.make() +let _formatter = Intl.ListFormat.make(~locales=["en-US", "en-GB"]) +let _formatter = Intl.ListFormat.make( + ~locales=["en-US", "en-GB"], + ~options={style: #long, \"type": #conjunction}, +) +Intl.ListFormat.supportedLocalesOf(["en-US", "en-GB"])->ignore +Intl.ListFormat.supportedLocalesOf(["en-US", "en-GB"], ~options={localeMatcher: #lookup})->ignore + +let formatter = Intl.ListFormat.make(~options={style: #long, \"type": #conjunction}) + +formatter->Intl.ListFormat.resolvedOptions->Console.log +formatter->Intl.ListFormat.format(["one", "two", "three"])->Console.log +formatter->Intl.ListFormat.formatToParts(["one", "two", "three"])->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_LocaleTest.mjs b/tests/tests/src/core/intl/Core_Intl_LocaleTest.mjs new file mode 100644 index 0000000000..240ab30896 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_LocaleTest.mjs @@ -0,0 +1,46 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.Locale"); + +let _locale = new Intl.Locale("en-US"); + +let locale = new Intl.Locale("en-US", { + calendar: "hebrew", + collation: "compat", + hourCycle: "h24", + caseFirst: "upper", + numeric: true +}); + +console.log(locale.baseName); + +console.log(locale.calendar); + +console.log(locale.caseFirst); + +console.log(locale.collation); + +console.log(locale.hourCycle); + +console.log(locale.language); + +console.log(locale.numberingSystem); + +console.log(locale.numeric); + +console.log(locale.region); + +console.log(locale.script); + +console.log(locale.maximize()); + +console.log(locale.minimize()); + +export { + _locale, + locale, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_LocaleTest.res b/tests/tests/src/core/intl/Core_Intl_LocaleTest.res new file mode 100644 index 0000000000..fe9b0537b3 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_LocaleTest.res @@ -0,0 +1,27 @@ +Console.log("---") +Console.log("Intl.Locale") + +let _locale = Intl.Locale.make("en-US") +let locale = Intl.Locale.make( + "en-US", + ~options={ + calendar: #hebrew, + collation: #compat, + hourCycle: #h24, + caseFirst: #upper, + numeric: true, + }, +) + +locale->Intl.Locale.baseName->Console.log +locale->Intl.Locale.calendar->Console.log +locale->Intl.Locale.caseFirst->Console.log +locale->Intl.Locale.collation->Console.log +locale->Intl.Locale.hourCycle->Console.log +locale->Intl.Locale.language->Console.log +locale->Intl.Locale.numberingSystem->Console.log +locale->Intl.Locale.numeric->Console.log +locale->Intl.Locale.region->Console.log +locale->Intl.Locale.script->Console.log +locale->Intl.Locale.maximize->Console.log +locale->Intl.Locale.minimize->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.mjs b/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.mjs new file mode 100644 index 0000000000..63c1f22d6a --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.mjs @@ -0,0 +1,58 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + +import * as Primitive_option from "rescript/lib/es6/Primitive_option.js"; +import * as Intl_NumberFormat_Grouping from "rescript/lib/es6/Intl_NumberFormat_Grouping.js"; + +console.log("---"); + +console.log("Intl.NumberFormat"); + +let currencyFormatter = new Intl.NumberFormat(["fr-FR"], { + currency: "EUR", + style: "currency" +}); + +console.log(Intl.NumberFormat.supportedLocalesOf([ + "fr-FR", + "en-US" +])); + +console.log(currencyFormatter.format(123.23)); + +let roundingFormatter = new Intl.NumberFormat(undefined, { + roundingIncrement: 500, + minimumFractionDigits: 2, + maximumFractionDigits: 2 +}); + +let groupingFormatter1 = new Intl.NumberFormat(undefined, { + useGrouping: Primitive_option.some(true) +}); + +let groupingFormatter2 = new Intl.NumberFormat(undefined, { + useGrouping: "auto" +}); + +let sigFormatter = new Intl.NumberFormat(undefined, { + minimumIntegerDigits: 1, + minimumFractionDigits: 1, + maximumFractionDigits: 1, + minimumSignificantDigits: 1, + maximumSignificantDigits: 1 +}); + +let options = sigFormatter.resolvedOptions(); + +console.log(options); + +console.log(Intl_NumberFormat_Grouping.parseJsValue(options.useGrouping)); + +export { + currencyFormatter, + roundingFormatter, + groupingFormatter1, + groupingFormatter2, + sigFormatter, + options, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.res b/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.res new file mode 100644 index 0000000000..8a126cec88 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_NumberFormatTest.res @@ -0,0 +1,43 @@ +Console.log("---") +Console.log("Intl.NumberFormat") + +let currencyFormatter = Intl.NumberFormat.make( + ~locales=["fr-FR"], + ~options={currency: "EUR", style: #currency}, +) + +Console.log(Intl.NumberFormat.supportedLocalesOf(["fr-FR", "en-US"])) +Console.log(currencyFormatter->Intl.NumberFormat.format(123.23)) + +let roundingFormatter = Intl.NumberFormat.make( + ~options={ + roundingIncrement: #500, + minimumFractionDigits: #2, + maximumFractionDigits: #2, + }, +) + +let groupingFormatter1 = Intl.NumberFormat.make( + ~options={ + useGrouping: Intl.NumberFormat.Grouping.fromBool(true), + }, +) +let groupingFormatter2 = Intl.NumberFormat.make( + ~options={ + useGrouping: Intl.NumberFormat.Grouping.fromString(#auto), + }, +) + +let sigFormatter = Intl.NumberFormat.make( + ~options={ + minimumIntegerDigits: #1, + minimumFractionDigits: #1, + maximumFractionDigits: #1, + minimumSignificantDigits: #1, + maximumSignificantDigits: #1, + }, +) + +let options = sigFormatter->Intl.NumberFormat.resolvedOptions +Console.log(options) +options.useGrouping->Intl_NumberFormat.Grouping.parseJsValue->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.mjs b/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.mjs new file mode 100644 index 0000000000..222817ddfc --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.mjs @@ -0,0 +1,37 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.PluralRules"); + +new Intl.PluralRules(); + +new Intl.PluralRules([ + "en-US", + "en-GB" +]); + +let _formatter = new Intl.PluralRules(undefined, { + type: "ordinal", + minimumSignificantDigits: 3, + maximumSignificantDigits: 5 +}); + +let formatter = new Intl.PluralRules(["en-US"], { + type: "ordinal", + minimumSignificantDigits: 3, + maximumSignificantDigits: 5 +}); + +console.log(formatter.resolvedOptions()); + +console.log(formatter.select(2.0)); + +console.log(formatter.select(2)); + +export { + _formatter, + formatter, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.res b/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.res new file mode 100644 index 0000000000..3262ee5b61 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_PluralRulesTest.res @@ -0,0 +1,33 @@ +Console.log("---") +Console.log("Intl.PluralRules") + +let _formatter = Intl.PluralRules.make() +let _formatter = Intl.PluralRules.make(~locales=["en-US", "en-GB"]) +let _formatter = Intl.PluralRules.make( + ~options={ + \"type": #ordinal, + maximumSignificantDigits: #5, + minimumSignificantDigits: #3, + }, +) +let formatter = Intl.PluralRules.make( + ~locales=["en-US"], + ~options={ + \"type": #ordinal, + maximumSignificantDigits: #5, + minimumSignificantDigits: #3, + }, +) + +formatter->Intl.PluralRules.resolvedOptions->Console.log + +formatter->Intl.PluralRules.select(2.0)->Console.log +formatter->Intl.PluralRules.selectInt(2)->Console.log + +// doesn't appear to work in node v16 +// formatter->Intl.PluralRules.selectBigInt(BigInt.fromInt(2))->Console.log +// formatter +// ->Intl.PluralRules.selectRangeBigInt(~start=BigInt.fromInt(1), ~end=BigInt.fromInt(3)) +// ->Console.log +// formatter->Intl.PluralRules.selectRange(~start=1., ~end=3.)->Console.log +// formatter->Intl.PluralRules.selectRangeInt(~start=1, ~end=3)->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.mjs b/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.mjs new file mode 100644 index 0000000000..54d732a0ca --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.mjs @@ -0,0 +1,47 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.RelativeTimeFormat"); + +Intl.RelativeTimeFormat.supportedLocalesOf([ + "en-US", + "en-GB" +]); + +Intl.RelativeTimeFormat.supportedLocalesOf([ + "en-US", + "en-GB" +], { + localeMatcher: "lookup" +}); + +new Intl.RelativeTimeFormat(); + +new Intl.RelativeTimeFormat([ + "en-US", + "en-GB" +]); + +let _formatter = new Intl.RelativeTimeFormat(undefined, { + numeric: "always", + style: "narrow" +}); + +let formatter = new Intl.RelativeTimeFormat(["en-US"], { + numeric: "always", + style: "narrow" +}); + +console.log(formatter.resolvedOptions()); + +console.log(formatter.format(3, "hour")); + +console.log(formatter.formatToParts(3, "hour")); + +export { + _formatter, + formatter, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.res b/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.res new file mode 100644 index 0000000000..e246525df9 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_RelativeTimeFormatTest.res @@ -0,0 +1,29 @@ +Console.log("---") +Console.log("Intl.RelativeTimeFormat") + +Intl.RelativeTimeFormat.supportedLocalesOf(["en-US", "en-GB"])->ignore +Intl.RelativeTimeFormat.supportedLocalesOf( + ["en-US", "en-GB"], + ~options={localeMatcher: #lookup}, +)->ignore + +let _formatter = Intl.RelativeTimeFormat.make() +let _formatter = Intl.RelativeTimeFormat.make(~locales=["en-US", "en-GB"]) +let _formatter = Intl.RelativeTimeFormat.make( + ~options={ + numeric: #always, + style: #narrow, + }, +) +let formatter = Intl.RelativeTimeFormat.make( + ~locales=["en-US"], + ~options={ + numeric: #always, + style: #narrow, + }, +) + +formatter->Intl.RelativeTimeFormat.resolvedOptions->Console.log + +formatter->Intl.RelativeTimeFormat.format(3, #hour)->Console.log +formatter->Intl.RelativeTimeFormat.formatToParts(3, #hour)->Console.log diff --git a/tests/tests/src/core/intl/Core_Intl_SegmenterTest.mjs b/tests/tests/src/core/intl/Core_Intl_SegmenterTest.mjs new file mode 100644 index 0000000000..f44116a73e --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_SegmenterTest.mjs @@ -0,0 +1,50 @@ +// Generated by ReScript, PLEASE EDIT WITH CARE + + +console.log("---"); + +console.log("Intl.Segmenter"); + +Intl.Segmenter.supportedLocalesOf([ + "en-US", + "en-GB" +]); + +Intl.Segmenter.supportedLocalesOf([ + "en-US", + "en-GB" +], { + localeMatcher: "lookup" +}); + +new Intl.Segmenter(); + +new Intl.Segmenter([ + "en-US", + "en-GB" +]); + +let _formatter = new Intl.Segmenter(undefined, { + granularity: "word" +}); + +let formatter = new Intl.Segmenter(["en-US"], { + granularity: "word" +}); + +console.log(formatter.resolvedOptions()); + +let segments = formatter.segment("This is a sentence with several words"); + +console.log(segments); + +console.log(segments.containing()); + +console.log(segments.containing(1)); + +export { + _formatter, + formatter, + segments, +} +/* Not a pure module */ diff --git a/tests/tests/src/core/intl/Core_Intl_SegmenterTest.res b/tests/tests/src/core/intl/Core_Intl_SegmenterTest.res new file mode 100644 index 0000000000..a95819a649 --- /dev/null +++ b/tests/tests/src/core/intl/Core_Intl_SegmenterTest.res @@ -0,0 +1,27 @@ +Console.log("---") +Console.log("Intl.Segmenter") + +Intl.Segmenter.supportedLocalesOf(["en-US", "en-GB"])->ignore +Intl.Segmenter.supportedLocalesOf(["en-US", "en-GB"], ~options={localeMatcher: #lookup})->ignore + +let _formatter = Intl.Segmenter.make() +let _formatter = Intl.Segmenter.make(~locales=["en-US", "en-GB"]) +let _formatter = Intl.Segmenter.make( + ~options={ + granularity: #word, + }, +) +let formatter = Intl.Segmenter.make( + ~locales=["en-US"], + ~options={ + granularity: #word, + }, +) + +formatter->Intl.Segmenter.resolvedOptions->Console.log +let segments = formatter->Intl.Segmenter.segment("This is a sentence with several words") + +Console.log(segments) + +Intl.Segments.containing(segments)->Console.log +Intl.Segments.containingWithIndex(segments, 1)->Console.log