import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.DynamicTest;
import org.junit.jupiter.api.TestFactory;
import ucar.units.Converter;
import ucar.units.Unit;
import ucar.units.UnitFormatManager;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
class ConversionTest {
@TestFactory
Stream<DynamicTest> conversionTests() {
String[] unitNames = new String[]{
"degK",
"K",
"deg_K",
"degsK",
"F",
"deg_F",
"degF",
"C",
"degC",
"deg_C"
};
List<Unit> units = Arrays.stream(unitNames)
.map(this::parse)
.collect(Collectors.toList());
return IntStream.range(0, units.size())
.mapToObj(fromIndex -> IntStream.range(0, units.size())
.mapToObj(toIndex ->
DynamicTest.dynamicTest(unitNames[fromIndex] + " to " + unitNames[toIndex],
() -> Assertions.assertDoesNotThrow(() -> convertTest(units.get(fromIndex), units.get(toIndex), 10.0)))
).collect(Collectors.toList()))
.flatMap(List::stream);
}
private double convertTest(Unit from, Unit to, double value) {
try {
if (!from.isCompatible(to)) {
throw new RuntimeException("Units not compatible");
}
Converter converter = from.getConverterTo(to);
return converter.convert(value);
} catch (Exception ex) {
throw new RuntimeException("Failed to convert", ex);
}
}
private Unit parse(String name) {
try {
return UnitFormatManager.instance().parse(name);
} catch (Exception e) {
throw new RuntimeException("Failed to parse", e);
}
}
}
```</div>
Discussed in #789
Originally posted by keitheweber August 16, 2021
I wrote a simple set of unit tests that would test converting from one unit to another when instantiating the unit objects by parsing a string. I am not sure what I am doing wrong, but most of these fail. It appears that the alias names defined in https://www.unidata.ucar.edu/software/udunits/udunits-2.2.28/udunits2-common.xml are not being honored?
Here's the source code for the unit tests