Skip to content

Commit

Permalink
Add expect/to_loosely_equal
Browse files Browse the repository at this point in the history
  • Loading branch information
maxdeviant committed May 14, 2024
1 parent 611ec63 commit f6281b9
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 0 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

### Added

- Added `expect/to_loosely_equal` for asserting on `Float` values.

## [0.2.2] - 2024-05-06

### Changed
Expand Down
27 changes: 27 additions & 0 deletions src/startest/expect.gleam
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//// Assertions to be used in tests.

import exception
import gleam/float
import gleam/option.{type Option, None, Some}
import gleam/string
import startest/assertion_error.{AssertionError}
Expand Down Expand Up @@ -138,3 +139,29 @@ pub fn to_not_throw(f: fn() -> a) -> a {
|> assertion_error.raise
}
}

/// Asserts that the given `Float` is equal to the expected `Float` within the
/// provided tolerance.
pub fn to_loosely_equal(
actual: Float,
expected expected: Float,
tolerating tolerance: Float,
) -> Nil {
case float.loosely_equals(actual, expected, tolerance) {
True -> Nil
False ->
AssertionError(
string.concat([
"Expected ",
string.inspect(actual),
" to loosely equal ",
string.inspect(expected),
" with a tolerance of ",
string.inspect(tolerance),
]),
string.inspect(actual),
string.inspect(expected) <> " 卤 " <> string.inspect(tolerance),
)
|> assertion_error.raise
}
}
19 changes: 19 additions & 0 deletions test/startest/expect_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,22 @@ pub fn to_not_throw_tests() {
]),
])
}

pub fn to_loosely_equal_tests() {
describe("startest/expect", [
describe("to_loosely_equal", [
describe("given two loosely equal floats", [
it_passes(fn() {
2.0
|> expect.to_loosely_equal(2.4, tolerating: 0.5)
}),
]),
describe("given two loosely inequal floats", [
it_fails(fn() {
2.0
|> expect.to_loosely_equal(2.4, tolerating: 0.1)
}),
]),
]),
])
}

0 comments on commit f6281b9

Please sign in to comment.