Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Fix number truthiness by casting to individual types #857

Merged
merged 2 commits into from
May 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public static boolean evaluate(Object object) {
}

if (object instanceof Number) {
Copy link
Contributor

@boulter boulter May 16, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There are more subclasses of Number. While you don't have to handle them all, perhaps a sane default would be to use Number.floatValue() to avoid a potential bad cast to Float.

return ((Number) object).intValue() != 0;
return ((Number) object).doubleValue() != 0;
}

if (object instanceof String) {
Expand Down
31 changes: 30 additions & 1 deletion src/test/java/com/hubspot/jinjava/util/ObjectTruthValueTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import static org.assertj.core.api.Assertions.assertThat;

import org.junit.Before;
import org.junit.Test;

public class ObjectTruthValueTest {
Expand All @@ -15,6 +14,36 @@ public void itEvaluatesObjectsWithObjectTruthValue() {
.isFalse();
}

@Test
public void itEvaluatesIntegers() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

might be worth a utility function here that takes a and b and does the assertions so you're not duplicating the code for every type.

checkNumberTruthiness(1, 0);
}

@Test
public void itEvaluatesDoubles() {
checkNumberTruthiness(0.5, 0.0);
}

@Test
public void itEvaluatesLongs() {
checkNumberTruthiness(1L, 0L);
}

@Test
public void itEvaluatesShorts() {
checkNumberTruthiness((short) 1, (short) 0);
}

@Test
public void itEvaluatesFloats() {
checkNumberTruthiness(0.5f, 0.0f);
}

private void checkNumberTruthiness(Object a, Object b) {
assertThat(ObjectTruthValue.evaluate(a)).isTrue();
assertThat(ObjectTruthValue.evaluate(b)).isFalse();
}

private class TestObject implements HasObjectTruthValue {
private boolean objectTruthValue = false;

Expand Down