package mi.hdm.filesystem; import jdk.jfr.Description; import mi.hdm.recipes.Ingredient; import mi.hdm.recipes.Measurement; import mi.hdm.recipes.NutritionTable; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import java.lang.reflect.Method; import java.net.URL; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertEquals; class CSVParserTest { private final static CSVParser underTest = new CSVParser(); private static Method splitLine; private static Method getColIdxs; @BeforeAll public static void setupAll() throws NoSuchMethodException { //make private methods accessible for testing splitLine = underTest.getClass().getDeclaredMethod("splitLine", String.class, char.class); splitLine.setAccessible(true); getColIdxs = underTest.getClass().getDeclaredMethod("getColumnIndexes", String.class, char.class, String[].class); getColIdxs.setAccessible(true); } @Test @Description("Test if splitting a line in the CSV file works properly") public void testSplitLine() throws Exception { String line = "1,\"Nuts, pecans\",100 g,691,72g"; List<String> expected = List.of("1", "Nuts, pecans", "100 g", "691", "72g"); Object actual = splitLine.invoke(underTest, line, ','); assertEquals(expected, actual); } @Test @Description("Tests, if the columns to be extracted are found in the correct place and assigned with the correct index") public void testGetColumnIndexes() throws Exception { String header = ",name,calories,total_fat,saturated_fat,cholesterol,sodium"; String[] extract = new String[]{"name", "sodium"}; int[] expected = new int[]{1, 6}; int[] actual = (int[]) getColIdxs.invoke(underTest, header, ',', extract); assertArrayEquals(expected, actual); } @Test @Description("Test, if getting a list of ingredients from CSV works") public void testGetIngredientsFromCSV() throws Exception { String relative = "/data/testdata.csv"; URL resourceUrl = underTest.getClass().getResource(relative); assert resourceUrl != null; Path path = Paths.get(resourceUrl.toURI()); String absolutePath = path.toFile().getAbsolutePath(); String[] extract = new String[]{"name", "calories", "carbohydrate", "fat", "protein", "fiber", "sodium"}; List<Ingredient> expected = List.of(new Ingredient(Measurement.GRAM, "Cornstarch", new NutritionTable(381.0, 91.27, 0.05, 0.26, 0.9, 0.009))); List<Ingredient> actual = underTest.getIngredientsFromCSV(absolutePath, ',', extract); assertEquals(expected, actual); } }