Skip to content

Commit e8b3f87

Browse files
authored
Added equals and hashcode. Changed code to catch an empty String (#897)
Signed-off-by: dhoard <[email protected]>
1 parent 60c2553 commit e8b3f87

File tree

2 files changed

+68
-2
lines changed
  • prometheus-metrics-model/src
    • main/java/io/prometheus/metrics/model/snapshots
    • test/java/io/prometheus/metrics/model/snapshots

2 files changed

+68
-2
lines changed

prometheus-metrics-model/src/main/java/io/prometheus/metrics/model/snapshots/Unit.java

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package io.prometheus.metrics.model.snapshots;
22

3+
import java.util.Objects;
4+
35
/**
46
* Some pre-defined units for convenience. You can create your own units with
57
* <pre>
@@ -23,13 +25,13 @@ public class Unit {
2325
public static final Unit AMPERES = new Unit("amperes");
2426

2527
public Unit(String name) {
26-
this.name = name;
2728
if (name == null) {
2829
throw new NullPointerException("Unit name cannot be null.");
2930
}
30-
if (name.isEmpty()) {
31+
if (name.trim().isEmpty()) {
3132
throw new IllegalArgumentException("Unit name cannot be empty.");
3233
}
34+
this.name = name.trim();
3335
}
3436

3537
@Override
@@ -52,4 +54,17 @@ public static double secondsToMillis(double seconds) {
5254
public static double kiloBytesToBytes(double kilobytes) {
5355
return kilobytes * 1024;
5456
}
57+
58+
@Override
59+
public boolean equals(Object o) {
60+
if (this == o) return true;
61+
if (o == null || getClass() != o.getClass()) return false;
62+
Unit unit = (Unit) o;
63+
return Objects.equals(name, unit.name);
64+
}
65+
66+
@Override
67+
public int hashCode() {
68+
return Objects.hash(name);
69+
}
5570
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package io.prometheus.metrics.model.snapshots;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
import static org.junit.Assert.fail;
7+
8+
public class UnitTest {
9+
10+
@Test
11+
public void testEmpty() {
12+
try {
13+
new Unit(" ");
14+
fail("Expected IllegalArgumentException");
15+
} catch (IllegalArgumentException e) {
16+
// Expected
17+
}
18+
}
19+
20+
@Test
21+
public void testEquals1() {
22+
Unit unit1 = Unit.BYTES;
23+
Unit unit2 = new Unit("bytes");
24+
25+
Assert.assertEquals(unit2, unit1);
26+
}
27+
28+
@Test
29+
public void testEquals2() {
30+
Unit unit1 = new Unit("bytes ");
31+
Unit unit2 = new Unit("bytes");
32+
33+
Assert.assertEquals(unit2, unit1);
34+
}
35+
36+
@Test
37+
public void testEquals3() {
38+
Unit unit1 = new Unit(" bytes");
39+
Unit unit2 = new Unit("bytes");
40+
41+
Assert.assertEquals(unit2, unit1);
42+
}
43+
44+
@Test
45+
public void testEquals4() {
46+
Unit unit1 = new Unit(" bytes ");
47+
Unit unit2 = new Unit("bytes");
48+
49+
Assert.assertEquals(unit2, unit1);
50+
}
51+
}

0 commit comments

Comments
 (0)