]> git.somenet.org - pub/jan/dst18.git/blob - ass2-service/api/src/test/java/dst/ass2/proto/auth/ProtoSpecificationTest.java
Add template for assignment 2
[pub/jan/dst18.git] / ass2-service / api / src / test / java / dst / ass2 / proto / auth / ProtoSpecificationTest.java
1 package dst.ass2.proto.auth;
2
3 import io.grpc.MethodDescriptor;
4 import io.grpc.ServiceDescriptor;
5 import org.junit.Before;
6 import org.junit.Test;
7
8 import java.lang.reflect.InvocationTargetException;
9 import java.lang.reflect.Method;
10 import java.util.Map;
11 import java.util.function.Function;
12 import java.util.stream.Collectors;
13
14 import static org.hamcrest.CoreMatchers.hasItems;
15 import static org.junit.Assert.assertThat;
16
17 public class ProtoSpecificationTest {
18
19     private ClassLoader cl;
20     public static final String SERVICE_NAME = "dst.ass2.service.api.auth.proto.AuthService";
21     public static final String GRPC_CLASS_NAME = SERVICE_NAME + "Grpc";
22
23     @Before
24     public void setUp() throws Exception {
25         cl = ProtoSpecificationTest.class.getClassLoader();
26     }
27
28     @Test
29     public void generatedClass_exists() throws Exception {
30         try {
31             cl.loadClass(GRPC_CLASS_NAME);
32         } catch (ClassNotFoundException e) {
33             throw new AssertionError("Classpath did not contain expected gRPC service class", e);
34         }
35     }
36
37     @Test
38     public void generatedClass_hasMethods() throws Exception {
39         assertThat(getMethodDescriptors().keySet(), hasItems(
40                 SERVICE_NAME + "/authenticate",
41                 SERVICE_NAME + "/validateToken"
42         ));
43     }
44
45     private Map<String, MethodDescriptor> getMethodDescriptors() throws ClassNotFoundException {
46         return getMethodDescriptors(getServiceDescriptor(cl.loadClass(GRPC_CLASS_NAME)));
47     }
48
49     private Map<String, MethodDescriptor> getMethodDescriptors(ServiceDescriptor sd) {
50         return sd.getMethods().stream()
51                 .collect(Collectors.toMap(
52                         MethodDescriptor::getFullMethodName,
53                         Function.identity()
54                 ));
55     }
56
57     private ServiceDescriptor getServiceDescriptor(Class<?> grpcClass) {
58         try {
59             Method getServiceDescriptor = grpcClass.getDeclaredMethod("getServiceDescriptor");
60             getServiceDescriptor.setAccessible(true);
61             return (ServiceDescriptor) getServiceDescriptor.invoke(null);
62         } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
63             throw new RuntimeException("Error finding service descriptor in " + grpcClass.getName(), e);
64         }
65     }
66 }