Skip to content

Commit

Permalink
Merge pull request #857 from HubSpot/number-truthy
Browse files Browse the repository at this point in the history
Fix number truthiness by casting to individual types
  • Loading branch information
jasmith-hs authored May 18, 2022
2 parents 2f5b7e3 + 1c2f91d commit 8a316e3
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
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) {
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() {
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

0 comments on commit 8a316e3

Please sign in to comment.