### Example gleam.toml with Deno Permissions Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/configuration.md A complete example of a gleam.toml file including the necessary Deno JavaScript runtime permissions. ```toml name = "my_project" version = "1.0.0" [javascript.deno] allow_read = ["gleam.toml", "test", "build"] ``` -------------------------------- ### Gleeunit Test File Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/INDEX.md Example of a basic Gleeunit test file in Gleam. It includes the main function to run tests and a simple addition test case using the assert keyword. ```gleam // test/my_app_test.gleam import gleeunit pub fn main() { gleeunit.main() } pub fn addition_test() { let assert 2 = 1 + 1 } ``` -------------------------------- ### Usage Example for State Tracking Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Demonstrates how to initialize state, record test outcomes (pass/fail), and finalize reporting. ```gleam import gleeunit/internal/reporting pub fn track_tests() { let state = reporting.new_state() let state = reporting.test_passed(state) let state = reporting.test_passed(state) let state = reporting.test_failed(state, "my_test", "some_function", error) let exit_code = reporting.finished(state) } ``` -------------------------------- ### Create a Basic Test File Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Example of a minimal test file structure for Gleeunit. Imports the library and defines a simple test function. ```gleam import gleeunit pub fn main() { gleeunit.main() } pub fn example_test() { let assert True = True } ``` -------------------------------- ### eunit_missing Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Reports a missing EUnit error and returns an error result, indicating an incomplete Erlang installation. ```APIDOC ## eunit_missing ### Description Reports a missing EUnit error and returns an error result. This function is called when EUnit libraries are not found, suggesting an incomplete Erlang installation. ### Signature ```gleam pub fn eunit_missing() -> Result(never, Nil) ``` ### Return Type `Result(never, Nil)` — Always returns `Error(Nil)` ### Behavior Prints an error message to stderr explaining that EUnit libraries are not found, indicating that the Erlang installation is incomplete. This is typically called when the Erlang runtime doesn't have the EUnit test framework available. ### Error Message: ``` Error: EUnit libraries not found. Your Erlang installation seems to be incomplete. If you installed Erlang using a package manager ensure that you have installed the full Erlang distribution instead of a stripped-down version. ``` ### Usage Example: ```gleam import gleeunit/internal/reporting pub fn run_erlang_tests() { case check_eunit_available() { False -> reporting.eunit_missing() True -> { // Run tests } } } ``` ``` -------------------------------- ### Gleeunit Test Failure Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md An example of the output format when a Gleeunit test fails. It includes the file, test name, assertion code, and the differing values. ```text assert test/my_test.gleam:42 test: my_test.compare_test code: assert a == b left: 5 right: 3 info: Assertion failed. ``` -------------------------------- ### Gleeunit Test Output Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md The expected output after running tests shows dots for each passing test, followed by a summary of the test results. ```text .. 2 passed, no failures ``` -------------------------------- ### Add Gleeunit Dev Dependency Source: https://github.com/lpil/gleeunit/blob/main/README.md Install gleeunit as a development dependency using the gleam CLI. ```sh gleam add gleeunit@1 --dev ``` -------------------------------- ### Running Gleeunit Tests Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Execute Gleeunit tests from your project's root directory using the `gleam test` command. This example shows the command and expected output. ```bash gleam test ``` ```text .. 2 passed, no failures ``` -------------------------------- ### Basic Gleam Test Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/00_START_HERE.md A simple Gleam test function that uses the `assert` keyword for verification. Place this in a `test/` directory file ending with `_test.gleam` to have it automatically discovered by `gleam test`. ```gleam pub fn addition_test() { let assert 2 = 1 + 1 } ``` -------------------------------- ### Gleam Pattern Match Failure Examples Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md Demonstrates various scenarios where a `let assert` pattern match can fail due to list structure, type mismatch, or expected versus actual results. ```gleam pub fn pattern_match_fails_test() { let assert [x, y] = [1] // Fails - list has 1 element, pattern expects 2 } ``` ```gleam pub fn type_mismatch_test() { let assert "string" = 42 // Fails - type mismatch } ``` ```gleam pub fn match_with_message_test() { let assert Ok(value) = Error("failed") as "Expected Ok result" } ``` -------------------------------- ### Testing Lists in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Illustrates how to assert the contents of a list in Gleam. This example appends elements to a list and then asserts the final list's structure. ```gleam pub fn list_test() { let assert [1, 2, 3] = [1] |> list.append([2, 3]) } ``` -------------------------------- ### Using External JavaScript (FFI) Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Example of using external JavaScript functions via Foreign Function Interface (FFI). Ensure the external JavaScript file exists and is correctly referenced. ```gleam @external(javascript, "./my_test_ffi.mjs", "read_file") pub fn read_file(path: String) -> Result(String, Nil) pub fn file_reading_test() { let result = read_file("test.txt") let assert Ok(content) = result } ``` -------------------------------- ### EUnit Not Found Error Output Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md This is the error output when EUnit libraries are not found in the Erlang runtime. Ensure a complete Erlang installation. ```text Error: EUnit libraries not found. Your Erlang installation seems to be incomplete. If you installed Erlang using a package manager ensure that you have installed the full Erlang distribution instead of a stripped-down version. ``` -------------------------------- ### Show Expression Value Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-gleam-panic.md Demonstrates how to handle different `ExpressionKind` variants to display the appropriate value or indicate if an expression was unevaluated. This is useful for debugging and error reporting. ```gleam import gleeunit/internal/gleam_panic pub fn show_expression_value(expr: gleam_panic.AssertedExpression) { case expr.kind { gleam_panic.Literal(value:) -> { // Show the literal value } gleam_panic.Expression(value:) -> { // Show the evaluated expression result } gleam_panic.Unevaluated -> { // Don't show a value (expression didn't evaluate) } } } ``` -------------------------------- ### Basic Gleeunit Test Structure Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md This snippet shows the basic structure of a Gleeunit test file, including the main function and example tests using the `assert` keyword. ```gleam import gleeunit pub fn main() { gleeunit.main() } pub fn addition_test() { let assert 2 = 1 + 1 } pub fn string_test() { let assert "hello" = "hel" <> "lo" } ``` -------------------------------- ### Split String by Delimiter Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Divides a string into a list of substrings based on a specified delimiter. This example splits by a comma. ```gleam import gleam/string pub fn string_split_test() { let result = "a,b,c" |> string.split(",") let assert ["a", "b", "c"] = result } ``` -------------------------------- ### Find Element in List Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Finds the first element in a list that matches a specific condition. This example searches for the number 2. ```gleam import gleam/list pub fn list_find_test() { let result = [1, 2, 3] |> list.find(fn(x) { x == 2 }) let assert Ok(2) = result } ``` -------------------------------- ### Legacy Gleeunit Test Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/INDEX.md Write tests using the legacy approach with the `should` module for assertions. This method involves piping the result of an expression to a `should` function. ```gleam import gleeunit/should pub fn my_test() { 2 + 2 |> should.equal(4) } ``` -------------------------------- ### Parameterized Testing Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Simulates parameterized testing by iterating over a list of test cases within a single test function. Each case includes inputs and the expected output. ```gleam pub fn test_many_additions() { let test_cases = [ #(1, 1, 2), #(2, 3, 5), #(-1, 1, 0), #(0, 0, 0), ] test_cases |> list.each(fn(case) { let #(a, b, expected) = case let result = a + b let assert expected = result }) } ``` -------------------------------- ### Get String Length Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Calculates the number of characters in a string. Useful for validation or display purposes. ```gleam import gleam/string pub fn string_length_test() { let assert 5 = "hello" |> string.length() } ``` -------------------------------- ### Legacy Assertion Style with `should` Module Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md This snippet demonstrates the legacy assertion style using the `gleeunit/should` module. It includes examples for checking equality and verifying `Ok` results. ```gleam import gleeunit/should pub fn equality_test() { 2 + 2 |> should.equal(4) } pub fn ok_test() { Ok(42) |> should.be_ok() |> should.equal(42) } ``` -------------------------------- ### Modern Gleeunit Test Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/INDEX.md Write tests using the modern approach with the `assert` keyword for concise assertions. This is the preferred method for writing tests in Gleeunit. ```gleam pub fn my_test() { let assert 4 = 2 + 2 } ``` -------------------------------- ### Handle Missing EUnit Error Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Reports a missing EUnit error and returns an error result. This function is called when EUnit libraries are not found, indicating an incomplete Erlang installation. ```gleam import gleeunit/internal/reporting pub fn run_erlang_tests() { case check_eunit_available() { False -> reporting.eunit_missing() True -> { // Run tests } } } ``` -------------------------------- ### Catching Assertion Failures in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md Provides an example of how to catch assertion failures in Gleam tests, distinguishing between different types of assertion failures like binary operators or function calls. ```gleam import gleeunit/internal/gleam_panic case gleam_panic.from_dynamic(error) { Ok(GleamPanic(kind: gleam_panic.Assert(kind: assert_kind, ..), ..)) -> { case assert_kind { gleam_panic.BinaryOperator(operator, left, right) -> { // Handle binary operator assertion failure } gleam_panic.FunctionCall(arguments) -> { // Handle function call assertion failure } gleam_panic.OtherExpression(expression) -> { // Handle other expression assertion failure } } } _ -> Nil } ``` -------------------------------- ### main() Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/INDEX.md Discovers and runs all tests within the project. ```APIDOC ## main() ### Description Discovers and runs all tests. ### Function Signature `main() -> Nil` ### Module gleeunit ``` -------------------------------- ### Configure Gleeunit Main Entry Point Source: https://github.com/lpil/gleeunit/blob/main/README.md Set up the main function in your test file to run gleeunit. ```gleam import gleeunit pub fn main() { gleeunit.main() } ``` -------------------------------- ### Create First Gleeunit Test File Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md A basic gleeunit test file includes the necessary import and calls gleeunit.main(). It also defines test functions using the `pub fn` syntax. ```gleam import gleeunit pub fn main() { gleeunit.main() } pub fn addition_test() { let assert 2 = 1 + 1 } pub fn subtraction_test() { let assert 1 = 2 - 1 } ``` -------------------------------- ### Erlang Eunit Options Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/types.md Defines the configuration options available for Eunit when running tests on the Erlang VM, including reporting and timeout scaling. ```text EunitOption (configuration) ├→ Verbose ├→ NoTty ├→ Report(ReportModuleName, List(GleeunitProgressOption)) │ ├→ ReportModuleName (GleeunitProgress) │ └→ GleeunitProgressOption (Colored) └→ ScaleTimeouts(Int) ``` -------------------------------- ### Get List Length Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Calculates and asserts the number of elements in a list. Useful for verifying list sizes after operations. ```gleam import gleam/list pub fn list_length_test() { let assert 3 = [1, 2, 3] |> list.length() } ``` -------------------------------- ### Replace Substring in String Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Replaces all occurrences of a specified substring within a string with another substring. This example replaces 'world' with 'gleam'. ```gleam import gleam/string pub fn string_replace_test() { let result = "hello world" |> string.replace("world", "gleam") let assert "hello gleam" = result } ``` -------------------------------- ### Module Initialization Test Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Tests module-level functions. Ensure the module and test files are correctly set up. ```gleam pub fn default_timeout() -> Int { 5000 } ``` ```gleam import config pub fn default_timeout_test() { let assert 5000 = config.default_timeout() } ``` -------------------------------- ### Deno JavaScript Runtime Configuration Source: https://github.com/lpil/gleeunit/blob/main/README.md Configure Deno's read permissions in `gleam.toml` when using gleeunit with the JavaScript runtime. ```toml [javascript.deno] allow_read = [ "gleam.toml", "test", "build", ] ``` -------------------------------- ### Run All Tests with Gleeunit Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/INDEX.md Execute all tests in your project using the `gleam test` command. Tests are discovered automatically and run when `gleeunit.main()` is invoked. ```bash gleam test # Run all tests ``` -------------------------------- ### Gleam Panic Format for let assert Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Displays the format for 'let assert' errors, including file, line, module, function, source code, matched value, and an informational message. ```text let assert : test: . code: value: info: ``` -------------------------------- ### Configure Deno for Gleeunit Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Specify file system access permissions for Deno when running Gleeunit tests. This is added to your `gleam.toml` file. ```toml [javascript.deno] allow_read = ["gleam.toml", "test", "build"] ``` -------------------------------- ### Inspect Complex Values Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Use `string.inspect()` to get a string representation of complex values for debugging purposes. This helps in understanding the structure and content of variables. ```gleam import gleam/string import gleam/io pub fn debug_test() { let complex_value = [1, 2, 3] io.println(string.inspect(complex_value)) // Prints: "[1, 2, 3]" } ``` -------------------------------- ### Platform Agnostic Test Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md This test runs on both Node.js and Deno environments without requiring any modifications. ```gleam // test/my_test.gleam // This runs on both Node.js and Deno pub fn platform_agnostic_test() { let assert 2 = 1 + 1 } ``` -------------------------------- ### Import and Use Shared Test Helpers Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Import helper modules into your test files to utilize shared functions like `create_test_user`. ```gleam // test/users_test.gleam import test_helpers pub fn user_creation_test() { let user = test_helpers.create_test_user() let assert "Test User" = user.name ``` -------------------------------- ### Basic Assertions with `assert` Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Use the `assert` keyword for straightforward equality checks. It supports various types including numbers, lists, options, and results. Assertions provide detailed failure information. ```gleam pub fn test_addition() { let assert 4 = 2 + 2 } ``` ```gleam pub fn test_list_operations() { let assert [1, 2, 3] = [1] |> list.append([2, 3]) } ``` ```gleam pub fn test_option() { let assert Some(value) = option.Some(42) let assert 42 = value } ``` ```gleam pub fn test_result() { let assert Ok(value) = result.Ok(100) let assert 100 = value } ``` -------------------------------- ### Deno JavaScript Runtime Permissions Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/configuration.md Configure Deno permissions in gleam.toml to allow gleeunit to read necessary files for test discovery and execution. ```toml allow_read = [ "gleam.toml", "test", "build", ] ``` -------------------------------- ### Analyze Gleam Panic Kind Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-gleam-panic.md Shows how to inspect the specific kind of a Gleam panic, such as Todo, Panic, LetAssert, or Assert. This allows for differentiated error handling based on the panic's origin. ```gleam import gleeunit/internal/gleam_panic pub fn analyze_panic_kind(panic: gleam_panic.GleamPanic) { case panic.kind { gleam_panic.Todo -> { // Code was not implemented } gleam_panic.Panic -> { // Explicit panic } gleam_panic.LetAssert(value:, ..) -> { // let assert failed, value shows what was matched } gleam_panic.Assert(start:, end:, kind:, ..) -> { // assert failed, can examine the expression kind } } } ``` -------------------------------- ### Expression Object Structure Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-gleam-panic.md This JavaScript object structure defines the format for expression objects within Gleam panic details. It includes start and end positions, the kind of expression, and its value if applicable. ```javascript { start: number, end: number, kind: "literal" | "expression" | "unevaluated", value: any, // When kind is "literal" or "expression" } ``` -------------------------------- ### Gleam Panic Format for assert Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Displays the format for 'assert' errors, including file, line, module, function, source code, left and right values for binary operators, and an informational message. ```text assert : test: . code: left: (for binary operators) right: info: ``` -------------------------------- ### Gleam Test Function Timeout Example Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md Illustrates a Gleam test function that might cause a timeout due to an infinite loop or a very long operation. Note that JavaScript test runners do not have a built-in timeout. ```gleam pub fn slow_test() { // Infinite loop or very long operation loop_forever() } ``` -------------------------------- ### Test Execution State Flow Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/types.md Illustrates the sequence of states and function calls during test execution, from initial state tracking to panic handling and assertion analysis. ```text State (tracks counts) ↓ test_passed() / test_failed() / test_skipped() (update state) ↓ GleamPanic (parsed from errors in test_failed) ↓ PanicKind (categorizes the panic) ├→ AssertKind (details of assert expression) │ ├→ BinaryOperator │ ├→ FunctionCall │ └→ OtherExpression └→ Panic / Todo / LetAssert / Assert AssertedExpression (represents sub-expressions) ↓ ExpressionKind (value availability) ├→ Literal(value) ├→ Expression(value) └→ Unevaluated ``` -------------------------------- ### Create User with Optional Email Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Defines a `User` type with an optional email field using `option.Option`. This demonstrates handling nested data structures. ```gleam import gleam/option pub type User { User(id: Int, name: String, email: option.Option(String)) } pub fn user_creation_test() { let user = User(1, "Alice", option.Some("alice@example.com")) let assert User(id: 1, name: "Alice", email: Some("alice@example.com")) = user } ``` -------------------------------- ### Testing Pure Functions Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Demonstrates testing pure Gleam functions, which are straightforward due to their predictable nature. ```gleam pub fn add(a: Int, b: Int) -> Int { a + b } ``` ```gleam pub fn multiply(a: Int, b: Int) -> Int { a * b } ``` ```gleam import math pub fn add_test() { let assert 5 = math.add(2, 3) } ``` ```gleam pub fn multiply_test() { let assert 15 = math.multiply(3, 5) } ``` ```gleam pub fn order_of_operations_test() { let result = math.add(2, 3) |> math.multiply(4) let assert 20 = result } ``` -------------------------------- ### be_none Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/should.md Asserts that an Option is None. Panics if the Option is Some. ```APIDOC ## be_none ### Description Assert that an `Option` is `None`. ### Signature ```gleam pub fn be_none(a: Option(a)) -> Nil ``` ### Parameters - **a** (`Option(a)`) - The option to check ### Return Type `Nil` ### Behavior If the option is `None`, returns `Nil`. If it's `Some(...)`, panics. ### Throws - panic: `a` is `Some(...)` ### Usage Example ```gleam import gleeunit/should import gleam/list pub fn empty_list_test() { [] |> list.first() |> should.be_none() } pub fn not_found_test() { [1, 2, 3] |> list.find(fn(x) { x > 10 }) |> should.be_none() } ``` ``` -------------------------------- ### gleeunit.main Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/main.md Finds and runs all test functions for the current project using Erlang's EUnit test framework on Erlang targets, or a custom JavaScript test runner on JavaScript targets. This is the only exported function most users need. ```APIDOC ## main ### Description Finds and runs all test functions for the current project using Erlang's EUnit test framework on Erlang targets, or a custom JavaScript test runner on JavaScript targets. This is the only exported function most users need. It discovers and runs all public functions in the `test` directory that end with `_test`. - On Erlang: Uses EUnit with verbose output, no TTY, colored progress reporting, and scaled timeouts (10x multiplier). - On JavaScript: Uses a custom runner that discovers `.mjs` files compiled from test `.gleam` files. - Sets process exit code to 0 on all tests passing, 1 on any failure or no tests found. A test that panics (including assertion failures) is considered a failure. ### Signature ```gleam pub fn main() -> Nil ``` ### Returns `Nil` — This function never returns normally; it calls `halt()` which terminates the process. ### Exit Codes | Code | Condition | |------|-----------| | 0 | All tests passed | | 1 | One or more test failures, or no tests found | ### Usage Example — Basic Setup: ```gleam // In test/my_app_test.gleam import gleeunit pub fn main() { gleeunit.main() } pub fn addition_test() { let assert 2 = 1 + 1 } pub fn subtraction_test() { let assert 1 = 2 - 1 } ``` Then run with: ```bash gleam test ``` ### Usage Example — Module Organization: ```gleam // test/my_app_test.gleam import gleeunit pub fn main() { gleeunit.main() } pub fn math_add_test() { let assert 5 = 2 + 3 } // test/utils_test.gleam pub fn string_concat_test() { let assert "hello world" = string_concat("hello", " world") } // test/nested/module_test.gleam pub fn nested_test() { let assert True = True } ``` All test functions discovered in `test/**/*.gleam` and `test/**/*.erl` are executed. ### Source `src/gleeunit.gleam:13` ``` -------------------------------- ### Testing Multiple Cases Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Illustrates testing various scenarios within a single test function for both arithmetic operations and list manipulations. ```gleam pub fn addition_various_cases_test() { let assert 0 = 0 + 0 let assert 5 = 2 + 3 let assert -1 = -3 + 2 let assert 100 = 50 + 50 } ``` ```gleam pub fn list_operations_test() { let assert [] = [] let assert [1] = [1] let assert [1, 2] = [1, 2] let assert True = [1, 2] |> list.length() == 2 } ``` -------------------------------- ### Gleam Panic Format for panic and todo Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Displays the format for 'panic' and 'todo' errors, including file, line, module, function, and an informational message. ```text panic : test: . info: ``` -------------------------------- ### Test Panic Handling Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Verify that your code correctly handles panics using external FFI or language-specific mechanisms. This snippet demonstrates catching a panic. ```gleam @external(erlang, "erlang", "catch") @external(javascript, "./test_ffi.mjs", "catch_exception") fn catch_panic(f: fn() -> t) -> Result(t, dynamic.Dynamic) pub fn panic_test() { let result = catch_panic(fn() { panic }) let assert Error(_) = result } ``` -------------------------------- ### Create New Test State Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Initializes a new test state with all counters set to zero. Use this at the beginning of a test run. ```gleam import gleeunit/internal/reporting pub fn initialize_test_run() { let state = reporting.new_state() // state is State(passed: 0, failed: 0, skipped: 0) } ``` -------------------------------- ### Create User with No Email Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Illustrates creating a `User` record where the optional email field is `None`. This shows how to represent the absence of a value. ```gleam import gleam/option pub type User { User(id: Int, name: String, email: option.Option(String)) } pub fn user_no_email_test() { let user = User(2, "Bob", option.None) let assert User(email: None, ..) = user } ``` -------------------------------- ### Run All Tests Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/main.md This is the only exported function most users need. It discovers and runs all public functions in the `test` directory that end with `_test`. On Erlang, it uses EUnit with verbose output, no TTY, colored progress reporting, and scaled timeouts. On JavaScript, it uses a custom runner that discovers `.mjs` files compiled from test `.gleam` files. Sets process exit code to 0 on all tests passing, 1 on any failure or no tests found. A test that panics (including assertion failures) is considered a failure. This function never returns normally; it calls `halt()` which terminates the process. ```gleam import gleeunit pub fn main() { gleeunit.main() } pub fn addition_test() { let assert 2 = 1 + 1 } pub fn subtraction_test() { let assert 1 = 2 - 1 } ``` ```bash gleam test ``` ```gleam // test/my_app_test.gleam import gleeunit pub fn main() { gleeunit.main() } pub fn math_add_test() { let assert 5 = 2 + 3 } // test/utils_test.gleam pub fn string_concat_test() { let assert "hello world" = string_concat("hello", " world") } // test/nested/module_test.gleam pub fn nested_test() { let assert True = True } ``` -------------------------------- ### Run Tests with Gleeunit Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Execute all tests in your project using the Gleam test runner. ```bash gleam test ``` -------------------------------- ### Catching Let Assert Failures in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md Shows how to use `gleam_panic.from_dynamic` to catch and inspect `PanicKind.LetAssert` errors, extracting the dynamic value that failed to match. ```gleam import gleeunit/internal/gleam_panic import gleam/dynamic case gleam_panic.from_dynamic(error) { Ok(GleamPanic(kind: gleam_panic.LetAssert(value, ..), ..)) -> { // value contains the dynamic value that failed to match // Use dynamic.string(value), dynamic.int(value), etc. to extract } _ -> Nil } ``` -------------------------------- ### Checking Options with `should.be_some` and `should.be_none` Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Assert whether an `Option` type is `Some` or `None` using `should.be_some` and `should.be_none`. `should.be_some` can be chained with `should.equal` to check the contained value. ```gleam import gleeunit/should pub fn test_some() { option.Some(42) |> should.be_some() |> should.equal(42) } ``` ```gleam import gleeunit/should pub fn test_none() { option.None |> should.be_none() } ``` -------------------------------- ### Report Assert Error Kind Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-gleam-panic.md Illustrates how to handle different types of failed assertions, including binary operations, function calls, and other expressions. This is useful for providing detailed feedback on assertion failures. ```gleam import gleeunit/internal/gleam_panic pub fn report_assert_error(assert_kind: gleam_panic.AssertKind) { case assert_kind { gleam_panic.BinaryOperator(operator:, left:, right:) -> { // e.g., "assert a && b" shows operator "&&" and left/right values } gleam_panic.FunctionCall(arguments:) -> { // e.g., "assert foo(x, y)" shows argument expressions } gleam_panic.OtherExpression(expression:) -> { // e.g., "assert x" shows variable value } } } ``` -------------------------------- ### Internal EunitOption Type Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/main.md Options passed to EUnit on Erlang targets. This includes enabling verbose output, disabling TTY-specific output, configuring the report module and options, and multiplying test timeouts by a given factor. ```gleam type EunitOption { Verbose NoTty Report(#(ReportModuleName, List(GleeunitProgressOption))) ScaleTimeouts(Int) } ``` -------------------------------- ### Checking Results with `should.be_ok` and `should.be_error` Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Verify if a `Result` type is `Ok` or `Error` using `should.be_ok` and `should.be_error`. These can be chained with `should.equal` to check the contained value. ```gleam import gleeunit/should pub fn test_ok() { result.Ok(42) |> should.be_ok() |> should.equal(42) } ``` ```gleam import gleeunit/should pub fn test_error() { result.Error("fail") |> should.be_error() |> should.equal("fail") } ``` -------------------------------- ### Simple Assertion in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Demonstrates a basic assertion in Gleam for a simple mathematical operation. This is used for straightforward equality checks. ```gleam pub fn math_test() { let assert 4 = 2 + 2 } ``` -------------------------------- ### Catching Todo Expressions in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/errors.md Demonstrates how to catch `todo` expressions, indicating unimplemented code, using gleeunit's error handling. This is helpful for tracking incomplete test cases. ```gleam import gleeunit/internal/gleam_panic case gleam_panic.from_dynamic(error) { Ok(GleamPanic(kind: gleam_panic.Todo, ..)) -> { // Handle unimplemented code } _ -> Nil } ``` -------------------------------- ### Assert Option is None Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/should.md Use `should.be_none` to assert that an `Option` is `None`. It panics if the option is `Some(...)`. This is useful for checking the absence of a value, like the result of `list.first()` on an empty list. ```gleam import gleeunit/should import gleam/list pub fn empty_list_test() { [] |> list.first() |> should.be_none() } pub fn not_found_test() { [1, 2, 3] |> list.find(fn(x) { x > 10 }) |> should.be_none() } ``` -------------------------------- ### Try Block for Result Chaining Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Uses a `use` block to sequentially execute operations that return `Result`. This simplifies handling multiple fallible operations. ```gleam import gleam/result pub fn result_try_test() { let result = { use x <- result.try(Ok(5)) use y <- result.try(Ok(3)) Ok(x + y) } let assert Ok(8) = result } ``` -------------------------------- ### Finalize Test Run and Report Summary Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-reporting.md Prints the test summary with colored output based on results and returns an appropriate exit code. Use after all tests have been executed. ```gleam import gleeunit/internal/reporting pub fn run_tests() { let state = reporting.new_state() let state = reporting.test_passed(state) let state = reporting.test_passed(state) let exit_code = reporting.finished(state) // Prints: "2 passed, no failures" in green // Returns: 0 } ``` -------------------------------- ### Define a Gleeunit Test Function Source: https://github.com/lpil/gleeunit/blob/main/README.md Write a test by defining a public function in the `test` directory whose name ends with `_test`. ```gleam pub fn some_function_test() { assert some_function() == "Hello!" } ``` -------------------------------- ### Legacy Should Assertion in Gleam Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/README.md Demonstrates the legacy 'should' syntax for assertions in Gleam. This method chains assertion calls to check for equality. ```gleam import gleeunit/should pub fn comparison_test() { 1 + 1 |> should.equal(2) } ``` -------------------------------- ### Testing with Fixtures Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Defines and uses test data generators (fixtures) to create reusable test data, such as default or custom user objects. ```gleam pub type User { User(id: Int, name: String, email: String) } pub fn default_user() -> User { User(1, "Test User", "test@example.com") } pub fn custom_user(id: Int, name: String, email: String) -> User { User(id, name, email) } // In tests: pub fn user_name_test() { let user = default_user() let assert "Test User" = user.name } ``` ```gleam pub fn custom_user_test() { let user = custom_user(2, "Alice", "alice@example.com") let assert "alice@example.com" = user.email } ``` -------------------------------- ### Append to a List Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Demonstrates how to append elements to an existing list in Gleam. This is a common operation for building or modifying lists. ```gleam import gleam/list pub fn list_append_test() { let result = [1, 2] |> list.append([3, 4]) let assert [1, 2, 3, 4] = result } ``` -------------------------------- ### Parse Gleam Panic from Dynamic Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/internal-gleam-panic.md Demonstrates how to convert a dynamic error from FFI into a structured GleamPanic type. Use this when handling errors returned from external code. ```gleam import gleeunit/internal/gleam_panic import gleam/dynamic pub fn handle_panic() { let error = ... // Some dynamic error from FFI case gleam_panic.from_dynamic(error) { Ok(panic) -> { panic.message // "Pattern match failed" panic.file // "test/my_test.gleam" panic.module // "my_test" panic.function // "my_test_function" panic.line // 42 } Error(_) -> Nil } } ``` -------------------------------- ### Shared Test Helper Module Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/USAGE_GUIDE.md Create helper modules (without `_test` in the name) to define reusable functions for your tests. These can be imported into your test files. ```gleam // test/test_helpers.gleam import gleam / result pub fn create_test_user() { User(id: 1, name: "Test User") } pub fn assert_ok(result: Result(a, e)) -> a { result |> result.unwrap(panic as "Expected Ok") } ``` -------------------------------- ### equal Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/api-reference/should.md Asserts that two values are equal using the `==` operator. Panics if the values are not equal, displaying both values in the panic message. ```APIDOC ## equal ### Description Asserts that two values are equal using the `==` operator. Panics with a formatted message if the values are not equal, showing both values for easy comparison. ### Signature ```gleam pub fn equal(a: t, b: t) -> Nil ``` ### Parameters - **a** (t) - The actual value - **b** (t) - The expected value ### Throws - panic: `a != b` ### Usage Example ```gleam import gleeunit/should pub fn addition_test() { 2 + 2 |> should.equal(4) } ``` ``` -------------------------------- ### PanicKind Source: https://github.com/lpil/gleeunit/blob/main/_autodocs/types.md Distinguishes between different types of Gleam runtime panics. ```APIDOC ## Type: PanicKind ### Description Distinguishes between different types of Gleam runtime panics. ### Variants - **Todo**: A `todo` expression was evaluated without implementation. - **Panic**: An explicit `panic` expression was evaluated. - **LetAssert**: A `let assert` pattern match failed. Includes byte offsets for the pattern and the value being matched. - **Fields**: `start` (Int), `end` (Int), `pattern_start` (Int), `pattern_end` (Int), `value` (dynamic.Dynamic) - **Assert**: An `assert` expression failed. Includes offsets for the assertion and detailed information about the expression type. - **Fields**: `start` (Int), `end` (Int), `expression_start` (Int), `kind` (AssertKind) ### Field Descriptions - `start` / `end`: Byte offsets in the source file for the entire expression. - `pattern_start` / `pattern_end`: Byte offsets for just the pattern in `let assert`. - `expression_start`: Byte offset where the expression begins (for `assert`). - `value`: The actual value that failed to match the pattern (for `let assert`). - `kind`: Detailed breakdown of what kind of expression was asserted (for `assert`). ```