Last active
March 8, 2024 20:27
-
-
Save idlehands/a16d0800db74d0ca772e1815018f67c1 to your computer and use it in GitHub Desktop.
RFC: Ideation for using assert values to compare items in a list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# option 1 - new function | |
assert_values_for_in_list( | |
expected_list: {[thing_1, thing_1], :string_keys}, | |
actual_list: return_value, # is list in all the examples | |
ordered: true, | |
fields: fields_for(Thing) | |
) | |
assert_values_for_in_list( | |
expected_list: [thing_2, thing_1], | |
actual_list: return_value, | |
ordered: false, | |
identifier_key: :id, # this would have to be required when ordered is false | |
fields: fields_for(Thing) | |
) | |
# option 2 - add an optional key to existing function | |
assert_values_for( | |
type: :ordered_list # default would be :single_map, or something like that, leavign this backwards compatible | |
expected: [thing_1, thing_2], | |
actual: return_value, | |
fields: fields_for(Thing) | |
) | |
assert_values_for( | |
type: :unordered_list | |
unique_identifier: : | |
expected: [thing_2, thing_1], | |
actual: return_value, | |
fields: fields_for(Thing) | |
) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Super early, working pass. Definitely happy path. | |
# This will stop and raise on the first element that mismatches. | |
# This doesn't provide feedback if the actual is longer than the expected. | |
# Would need to modify assert_values_for to optionally return errors instead of raising them to improve feedback | |
defp assert_values_for_in_list(opts) do | |
expected_list = opts |> Keyword.get(:expected_list) | |
actual_list = Keyword.get(opts, :actual_list) | |
assert length(expected_list_with_index) == length(expected_list) | |
fields = Keyword.get(opts, :fields) | |
ordered? = Keyword.get(opts, :ordered, true) | |
identifier_key = Keyword.get(opts, :identifier_key) | |
for {expected, index} <- Enum.with_index(expected_list) do | |
actual = | |
if ordered? do | |
Enum.at(actual_list, index) | |
else | |
Enum.find(actual_list, fn actual -> Map.get(actual, identifier_key) == Map.get(expected, identifier_key) end) | |
end | |
assert_values_for( | |
expected: expected, | |
actual: actual, | |
fields: fields | |
) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment