Skip to content

Commit

Permalink
Added equals and hashcode. Changed code to catch an empty String (#897)
Browse files Browse the repository at this point in the history
Signed-off-by: dhoard <doug.hoard@gmail.com>
  • Loading branch information
dhoard authored Nov 12, 2023
1 parent 60c2553 commit e8b3f87
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 2 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package io.prometheus.metrics.model.snapshots;

import java.util.Objects;

/**
* Some pre-defined units for convenience. You can create your own units with
* <pre>
Expand All @@ -23,13 +25,13 @@ public class Unit {
public static final Unit AMPERES = new Unit("amperes");

public Unit(String name) {
this.name = name;
if (name == null) {
throw new NullPointerException("Unit name cannot be null.");
}
if (name.isEmpty()) {
if (name.trim().isEmpty()) {
throw new IllegalArgumentException("Unit name cannot be empty.");
}
this.name = name.trim();
}

@Override
Expand All @@ -52,4 +54,17 @@ public static double secondsToMillis(double seconds) {
public static double kiloBytesToBytes(double kilobytes) {
return kilobytes * 1024;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Unit unit = (Unit) o;
return Objects.equals(name, unit.name);
}

@Override
public int hashCode() {
return Objects.hash(name);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package io.prometheus.metrics.model.snapshots;

import org.junit.Assert;
import org.junit.Test;

import static org.junit.Assert.fail;

public class UnitTest {

@Test
public void testEmpty() {
try {
new Unit(" ");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
// Expected
}
}

@Test
public void testEquals1() {
Unit unit1 = Unit.BYTES;
Unit unit2 = new Unit("bytes");

Assert.assertEquals(unit2, unit1);
}

@Test
public void testEquals2() {
Unit unit1 = new Unit("bytes ");
Unit unit2 = new Unit("bytes");

Assert.assertEquals(unit2, unit1);
}

@Test
public void testEquals3() {
Unit unit1 = new Unit(" bytes");
Unit unit2 = new Unit("bytes");

Assert.assertEquals(unit2, unit1);
}

@Test
public void testEquals4() {
Unit unit1 = new Unit(" bytes ");
Unit unit2 = new Unit("bytes");

Assert.assertEquals(unit2, unit1);
}
}

0 comments on commit e8b3f87

Please sign in to comment.