From e0dfa6aadef0b2fa9bc71a531fbbbf8fd12d6870 Mon Sep 17 00:00:00 2001
From: jez04 <david.jezek@post.cz>
Date: Wed, 13 Nov 2024 23:26:58 +0100
Subject: [PATCH] feat: uptade test

---
 .../structure/test/ClassStructureTest.java    | 119 +++++++++++++++---
 .../jez04/structure/test/StructureHelper.java |  64 +++++++---
 2 files changed, 150 insertions(+), 33 deletions(-)

diff --git a/src/test/java/jez04/structure/test/ClassStructureTest.java b/src/test/java/jez04/structure/test/ClassStructureTest.java
index 19d3dde..0e3694d 100644
--- a/src/test/java/jez04/structure/test/ClassStructureTest.java
+++ b/src/test/java/jez04/structure/test/ClassStructureTest.java
@@ -1,7 +1,7 @@
 package jez04.structure.test;
 
 import static org.junit.jupiter.api.Assertions.assertEquals;
-import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 import static org.junit.jupiter.api.Assertions.fail;
 
@@ -9,12 +9,15 @@ import java.io.IOException;
 import java.io.InputStreamReader;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.FileVisitor;
 import java.nio.file.Files;
+import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.Collection;
+import java.nio.file.attribute.BasicFileAttributes;
 import java.util.List;
 
+import org.junit.jupiter.api.BeforeAll;
 import org.junit.jupiter.api.Test;
 
 import cz.vsb.fei.lab.App;
@@ -23,13 +26,20 @@ import cz.vsb.fei.lab.ScoreNotLoaded;
 
 class ClassStructureTest {
 
-	StructureHelper helper = new StructureHelper();
+	static StructureHelper helper = new StructureHelper();
 	private static String className = "Score";
 
+	@BeforeAll
+	void printClassNames() {
+		for (String className : helper.getNameOfAllClasses()) {
+			System.out.println(className);
+		}
+	}
+
 	@Test
 	void scoreExistenceTest() {
-//		helper.classExist(className);
-		Class<?> c = Score.class;// helper.getClass(className);
+		helper.classExist(className);
+		Class<?> c = helper.getClass(className);
 		helper.hasProperty(c, "name", String.class, false);
 		helper.hasProperty(c, "points", int.class, false);
 		helper.hasMethod(c, "generate", Score.class);
@@ -37,14 +47,14 @@ class ClassStructureTest {
 
 	@Test
 	void scoreNotLoadedExistenceTest() {
-//		helper.classExist(className);
-		Class<?> c = ScoreNotLoaded.class;// helper.getClass("ScoreNotLoaded");
+		helper.classExist(className);
+		Class<?> c = helper.getClass("ScoreNotLoaded");
 		helper.hasProperty(c, "count", int.class, false);
 		helper.hasExtends(c, Exception.class);
 	}
 
 	@Test
-	void generateScoresTest() {
+	void generateScoresTest() throws Exception {
 		App app = new App();
 		assertTrue(app.generateScores(10).size() == 10);
 	}
@@ -56,7 +66,8 @@ class ClassStructureTest {
 				.size() > 1);
 	}
 
-	void loadScoresFromStreamExceptionTest() throws Exception, IllegalAccessException, InvocationTargetException, NoSuchMethodException, SecurityException {
+	void loadScoresFromStreamExceptionTest() throws Exception, IllegalAccessException, InvocationTargetException,
+			NoSuchMethodException, SecurityException {
 		App app = new App();
 		try {
 			app.loadScoresFromStream(new InputStreamReader(App.class.getResourceAsStream("/bestScores-err.csv")))
@@ -64,28 +75,102 @@ class ClassStructureTest {
 			fail("Exception not throwen!");
 		} catch (Exception e) {
 			assertEquals(ScoreNotLoaded.class, e.getClass(), "Excpectin exception of type ScoreNotLoaded");
-			int count = (int)ScoreNotLoaded.class.getDeclaredMethod("getCount").invoke(e);
+			int count = (int) ScoreNotLoaded.class.getDeclaredMethod("getCount").invoke(e);
 			assertTrue(count > 0, "Info about already parsed line missing");
 		}
 	}
 
-	void loadScoresTest() {
+	@Test
+	void loadScoresTest() throws Exception {
 		App app = new App();
-		app.loadScores();
+		List<Score> scores = app.loadScores();
+		assertNotNull(scores);
+		assertTrue(scores.size() > 0, "Collection is empty");
+	}
+
+	@Test
+	void loadScoresDisableCsvFailTest() throws Exception {
+		try {
+			Files.walkFileTree(Paths.get("."), new FileVisitor<Path>() {
+
+				@Override
+				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+					if (file.getFileName().toString().toLowerCase().endsWith(".csv")) {
+						file.toFile().renameTo(Paths.get(file.toString() + "-DISABLE").toFile());
+						return FileVisitResult.CONTINUE;
+					}
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+			});
+
+			App app = new App();
+			List<Score> scores = app.loadScores();
+			assertNotNull(scores);
+			assertTrue(scores.isEmpty(), "Collection have to be empty.");
+		} finally {
+			Files.walkFileTree(Paths.get("."), new FileVisitor<Path>() {
+
+				@Override
+				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
+					if (file.getFileName().toString().endsWith("-DISABLE")) {
+						String fileName = file.toString();
+						file.toFile().renameTo(
+								Paths.get(fileName.substring(0, fileName.length() - "-DISABLE".length())).toFile());
+						return FileVisitResult.CONTINUE;
+					}
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+
+				@Override
+				public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
+					return FileVisitResult.CONTINUE;
+				}
+			});
+
+		}
 	}
 
-	void saveScoresTest() throws IOException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+	void saveScoresTest() throws IOException, NoSuchMethodException, SecurityException, InstantiationException,
+			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
 		App app = new App();
 		app.saveScores(List.of(createScore("test", 1), createScore("test2", 15)), "test.csv");
 		assertEquals(2, Files.lines(Paths.get("test.csv")).count(),
 				"Expecting existent of file test.csv with 2 lines.");
 	}
 
-	private Score createScore(String name, int points) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+	private Score createScore(String name, int points) throws NoSuchMethodException, SecurityException,
+			InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
 		Constructor constructor = Score.class.getConstructor(String.class, int.class);
-		return (Score)constructor.newInstance(name, points);
+		return (Score) constructor.newInstance(name, points);
 	}
-	void saveScoresDirsTest() throws IOException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
+
+	void saveScoresDirsTest() throws IOException, NoSuchMethodException, SecurityException, InstantiationException,
+			IllegalAccessException, IllegalArgumentException, InvocationTargetException {
 		App app = new App();
 		app.saveScores(List.of(createScore("test", 1), createScore("test2", 15)), "test/subtest/test.csv");
 		assertEquals(2, Files.lines(Paths.get("test", "subtest", "test.csv")).count(),
diff --git a/src/test/java/jez04/structure/test/StructureHelper.java b/src/test/java/jez04/structure/test/StructureHelper.java
index 88fc05e..4ddbb17 100644
--- a/src/test/java/jez04/structure/test/StructureHelper.java
+++ b/src/test/java/jez04/structure/test/StructureHelper.java
@@ -9,6 +9,7 @@ import java.io.PrintStream;
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
 import java.net.URISyntaxException;
 import java.net.URL;
 import java.nio.file.FileVisitResult;
@@ -19,9 +20,10 @@ import java.nio.file.Paths;
 import java.nio.file.attribute.BasicFileAttributes;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
 
 import org.junit.jupiter.api.Assertions;
@@ -57,6 +59,7 @@ class StructureHelper {
 			return null;
 		}
 	}
+
 	public Class<?> getClass(String name) {
 		String className = allClasses.stream().filter(c -> c.endsWith(name)).findAny().orElse(null);
 		if (className == null) {
@@ -126,6 +129,7 @@ class StructureHelper {
 		List<Method> methods = Arrays.asList(interfaceDef.getDeclaredMethods());
 		return methods.stream().filter(m -> m.getName().matches(methodNameRegexp)).count();
 	}
+
 	public long countClassesRegexp(String classNameRegexp) {
 		return getNameOfAllClasses().stream().filter(className -> className.matches(classNameRegexp)).count();
 	}
@@ -181,10 +185,10 @@ class StructureHelper {
 	}
 
 	public Set<String> getNameOfAllClasses() {
-		List<String> initClassesName = new ArrayList<>();
-		dynamicaliFoundSomeClass(initClassesName);
-		initClassesName.addAll(List.of("cz.vsb.fei.lab.App", "lab.Routines", "lab.App", "lab.DrawingThread"));
-		for (String className : initClassesName) {
+		Set<String> allClassesName = new TreeSet<>();
+		dynamicaliFoundSomeClass(allClassesName);
+//		allClassesName.addAll(List.of("cz.vsb.fei.lab.App", "lab.Routines", "lab.App", "lab.DrawingThread"));
+		for (String className : allClassesName) {
 			try {
 				Class.forName(className);
 				break;
@@ -192,7 +196,6 @@ class StructureHelper {
 				System.out.println(String.format("Class '%s' cannot be loaded: %s", className, e.getMessage()));
 			}
 		}
-		Set<String> allClasses = new HashSet<>();
 		for (Package p : Package.getPackages()) {
 			if (p.getName().startsWith("java.") || p.getName().startsWith("com.") || p.getName().startsWith("jdk.")
 					|| p.getName().startsWith("javafx.") || p.getName().startsWith("org.")
@@ -204,23 +207,27 @@ class StructureHelper {
 			Configuration conf = new ConfigurationBuilder().addScanners(Scanners.SubTypes.filterResultsBy(pc -> true))
 					.forPackages(p.getName());
 			Reflections reflections = new Reflections(conf);
-			allClasses.addAll(reflections.getAll(Scanners.SubTypes.filterResultsBy(c -> {
+			allClassesName.addAll(reflections.getAll(Scanners.SubTypes.filterResultsBy(c -> {
 				System.out.println(">>> " + c);
 				return true;
 			})));
 		}
-		for (String string : allClasses) {
+		for (String string : allClassesName) {
 			System.out.println(string);
 		}
-		return allClasses;
+		return allClassesName;
 	}
 
-	public void dynamicaliFoundSomeClass(List<String> initClassesName) {
+	private static final List<String> dirsToSkip = List.of("jez04", "META-INF");
+	private static final List<String> filesToSkip = List.of("module-info.class");
+
+	public void dynamicaliFoundSomeClass(Set<String> allClassesName) {
 		URL myClassUrl = StructureHelper.class.getResource("ClassStructureTest.class");
 		myClassUrl.getFile();
 		try {
 			Path classRoot = Paths.get(myClassUrl.toURI());
-			while(!"test-classes".equals(classRoot.getFileName().toString()) && !"classes".equals(classRoot.getFileName().toString())) {
+			while (!"test-classes".equals(classRoot.getFileName().toString())
+					&& !"classes".equals(classRoot.getFileName().toString())) {
 				classRoot = classRoot.getParent();
 			}
 			if ("test-classes".equals(classRoot.getFileName().toString())) {
@@ -232,7 +239,7 @@ class StructureHelper {
 
 				@Override
 				public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
-					if (List.of("jez04", "META-INF").contains(dir.getFileName().toString())) {
+					if (dirsToSkip.contains(dir.getFileName().toString())) {
 						return FileVisitResult.SKIP_SUBTREE;
 					}
 					return FileVisitResult.CONTINUE;
@@ -240,18 +247,20 @@ class StructureHelper {
 
 				@Override
 				public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
-					System.out.println("VISIT: " + file);
-					if ("module-info.class".equals(file.getFileName().toString())) {
+					if (filesToSkip.contains(file.getFileName().toString())) {
 						return FileVisitResult.CONTINUE;
 					}
 					if (!file.getFileName().toString().endsWith(".class")) {
 						return FileVisitResult.CONTINUE;
 					}
+					if (file.getFileName().toString().contains("$")) {
+						return FileVisitResult.CONTINUE;
+					}
 					String foundClassName = classRootFinal.relativize(file).toString();
 					foundClassName = foundClassName.substring(0, foundClassName.length() - 6)
 							.replace(File.separatorChar, '.');
-					initClassesName.add(foundClassName);
-					return FileVisitResult.TERMINATE;
+					addClassAndAllRef(allClassesName, foundClassName);
+					return FileVisitResult.CONTINUE;
 				}
 
 				@Override
@@ -268,4 +277,27 @@ class StructureHelper {
 			e.printStackTrace();
 		}
 	}
+
+	private void addClassAndAllRef(Set<String> allClassesName, String foundClassName) {
+		allClassesName.add(foundClassName);
+		try {
+			Class<?> foundClass = Class.forName(foundClassName);
+			List.of(foundClass.getInterfaces()).stream().map(Class::getCanonicalName).forEach(allClassesName::add);
+			List.of(foundClass.getDeclaredClasses()).stream().map(Class::getCanonicalName).forEach(allClassesName::add);
+			List.of(foundClass.getDeclaredFields()).stream().map(Field::getType)
+					.map(clazz -> clazz.isArray() ? clazz.arrayType() : clazz).filter(Predicate.not(Class::isPrimitive))
+					.map(Class::getCanonicalName).forEach(allClassesName::add);
+			List.of(foundClass.getDeclaredMethods()).stream().map(Method::getReturnType)
+					.map(clazz -> clazz.isArray() ? clazz.arrayType() : clazz).filter(Predicate.not(Class::isPrimitive))
+					.map(Class::getCanonicalName).forEach(allClassesName::add);
+			List.of(foundClass.getDeclaredMethods()).stream().flatMap(m -> List.of(m.getParameters()).stream())
+					.map(Parameter::getType).map(clazz -> clazz.isArray() ? clazz.arrayType() : clazz)
+					.filter(Predicate.not(Class::isPrimitive)).map(Class::getCanonicalName)
+					.forEach(allClassesName::add);
+			allClassesName.add(foundClass.getSuperclass().getCanonicalName());
+		} catch (ClassNotFoundException e) {
+			// TODO Auto-generated catch block
+			e.printStackTrace();
+		}
+	}
 }
-- 
GitLab