Migrate from JUnit 4 to JUnit 5
Also resolves failing CI workflow:
https:
//github.com/KorAP/Kustvakt/actions/runs/6261950074/job/17017180336
Change-Id: I31a71419f0443118e973112e0f621d52c11fd81e
diff --git a/full/pom.xml b/full/pom.xml
index 194e4e6..7719546 100644
--- a/full/pom.xml
+++ b/full/pom.xml
@@ -211,13 +211,6 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.1.2</version>
- <dependencies>
- <dependency>
- <groupId>org.apache.maven.surefire</groupId>
- <artifactId>surefire-junit47</artifactId>
- <version>3.1.2</version>
- </dependency>
- </dependencies>
<configuration>
<reuseForks>true</reuseForks>
<forkCount>1</forkCount>
@@ -370,11 +363,6 @@
<!-- EM:done -->
<dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.13.2</version>
- </dependency>
- <dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.12.5</version>
@@ -690,24 +678,12 @@
<artifactId>jersey-test-framework-core</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.junit.jupiter</groupId>
- <artifactId>junit-jupiter</artifactId>
- </exclusion>
- </exclusions>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.test-framework.providers</groupId>
<artifactId>jersey-test-framework-provider-grizzly2</artifactId>
<version>${jersey.version}</version>
<scope>test</scope>
- <exclusions>
- <exclusion>
- <groupId>org.junit.jupiter</groupId>
- <artifactId>junit-jupiter</artifactId>
- </exclusion>
- </exclusions>
</dependency>
<!-- velocity -->
@@ -772,5 +748,11 @@
<version>5.15.0</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.junit.jupiter</groupId>
+ <artifactId>junit-jupiter</artifactId>
+ <version>5.10.0</version>
+ <scope>test</scope>
+ </dependency>
</dependencies>
</project>
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
index a36a27b..0de58d3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/APIAuthenticationTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.authentication;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.util.HashMap;
@@ -9,7 +9,7 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.fasterxml.jackson.databind.JsonNode;
@@ -35,46 +35,31 @@
private FullConfiguration config;
@Test
- public void testDeprecatedService () throws KustvaktException {
-
- String userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
-
- Response response = target().path(API_VERSION).path("auth")
- .path("apiToken").request()
- .header(Attributes.AUTHORIZATION, userAuthHeader)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
-
+ public void testDeprecatedService() throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ Response response = target().path(API_VERSION).path("auth").path("apiToken").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(StatusCodes.DEPRECATED, node.at("/errors/0/0").asInt());
}
@Test
- public void testCreateGetTokenContext () throws KustvaktException,
- IOException, InterruptedException, JOSEException {
+ public void testCreateGetTokenContext() throws KustvaktException, IOException, InterruptedException, JOSEException {
User user = new KorAPUser();
user.setUsername("testUser");
-
Map<String, Object> attr = new HashMap<>();
attr.put(Attributes.HOST, "localhost");
attr.put(Attributes.USER_AGENT, "java");
attr.put(Attributes.AUTHENTICATION_TIME, TimeUtils.getNow().toDate());
-
APIAuthentication auth = new APIAuthentication(config);
TokenContext context = auth.createTokenContext(user, attr);
-
// get token context
String authToken = context.getToken();
-// System.out.println(authToken);
+ // System.out.println(authToken);
context = auth.getTokenContext(authToken);
-
TokenType tokenType = context.getTokenType();
assertEquals(TokenType.API, tokenType);
- assertEquals("testUser", context.getUsername());
+ assertEquals(context.getUsername(), "testUser");
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
index 4873674..1aebf69 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/AuthenticationFilterTest.java
@@ -1,10 +1,10 @@
package de.ids_mannheim.korap.authentication;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.Attributes;
@@ -15,20 +15,12 @@
public class AuthenticationFilterTest extends SpringJerseyTest {
@Test
- public void testAuthenticationWithUnknownScheme ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION, "Blah blah")
- .get();
-
+ public void testAuthenticationWithUnknownScheme() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, "Blah blah").get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
-
- assertEquals("2001", n.at("/errors/0/0").asText());
- assertEquals("Authentication scheme is not supported.",
- n.at("/errors/0/1").asText());
- assertEquals("Blah", n.at("/errors/0/2").asText());
+ assertEquals(n.at("/errors/0/0").asText(), "2001");
+ assertEquals(n.at("/errors/0/1").asText(), "Authentication scheme is not supported.");
+ assertEquals(n.at("/errors/0/2").asText(), "Blah");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
index de8b9b1..f7c8a86 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapAuth3Test.java
@@ -10,50 +10,55 @@
import com.unboundid.util.ssl.SSLUtil;
import com.unboundid.util.ssl.TrustAllTrustManager;
import com.unboundid.util.ssl.TrustStoreTrustManager;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import java.security.GeneralSecurityException;
import static de.ids_mannheim.korap.authentication.LdapAuth3.*;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class LdapAuth3Test {
+
public static final String TEST_LDAP_CONF = "src/test/resources/test-ldap.conf";
+
public static final String TEST_LDAPS_CONF = "src/test/resources/test-ldaps.conf";
+
public static final String TEST_LDAPS_TS_CONF = "src/test/resources/test-ldaps-with-truststore.conf";
+
public static final String TEST_LDAP_USERS_LDIF = "src/test/resources/test-ldap-users.ldif";
+
private static final String keyStorePath = "src/test/resources/keystore.p12";
+
static InMemoryDirectoryServer server;
- @BeforeClass
- public static void startDirectoryServer() throws LDAPException, GeneralSecurityException {
+ @BeforeAll
+ static void startDirectoryServer() throws LDAPException, GeneralSecurityException {
InMemoryDirectoryServerConfig config = new InMemoryDirectoryServerConfig("dc=example,dc=com");
config.addAdditionalBindCredentials("cn=admin,dc=example,dc=com", "adminpassword");
config.setSchema(null);
-
final SSLUtil serverSSLUtil = new SSLUtil(new KeyStoreKeyManager(keyStorePath, "password".toCharArray(), "PKCS12", "server-cert"), new TrustStoreTrustManager(keyStorePath));
-
final SSLUtil clientSslUtil = new SSLUtil(new TrustAllTrustManager());
-
- config.setListenerConfigs(InMemoryListenerConfig.createLDAPConfig("LDAP", // Listener name
- null, // Listen address. (null = listen on all interfaces)
- 3268, // Listen port (0 = automatically choose an available port)
- clientSslUtil.createSSLSocketFactory()), // StartTLS factory
- InMemoryListenerConfig.createLDAPSConfig("LDAPS", // Listener name
- null, // Listen address. (null = listen on all interfaces)
- 3269, // Listen port (0 = automatically choose an available port)
- serverSSLUtil.createSSLServerSocketFactory(), clientSslUtil.createSSLSocketFactory()));
+ config.setListenerConfigs(// Listener name
+ InMemoryListenerConfig.createLDAPConfig(// Listener name
+ "LDAP", // Listen address. (null = listen on all interfaces)
+ null, // Listen port (0 = automatically choose an available port)
+ 3268, // StartTLS factory
+ clientSslUtil.createSSLSocketFactory()), // Listener name
+ InMemoryListenerConfig.createLDAPSConfig(// Listener name
+ "LDAPS", // Listen address. (null = listen on all interfaces)
+ null, // Listen port (0 = automatically choose an available port)
+ 3269, serverSSLUtil.createSSLServerSocketFactory(), clientSslUtil.createSSLSocketFactory()));
server = new InMemoryDirectoryServer(config);
-
String configPath = TEST_LDAP_USERS_LDIF;
server.importFromLDIF(true, configPath);
server.startListening();
}
- @AfterClass
- public static void shutDownDirectoryServer() {
+ @AfterAll
+ static void shutDownDirectoryServer() {
server.shutDown(true);
}
@@ -150,36 +155,35 @@
@Test
public void gettingMailAttributeForUid() throws LDAPException {
- assertEquals("testuser@example.com", LdapAuth3.getEmail("testuser", TEST_LDAP_CONF));
- assertEquals("peter@example.org", LdapAuth3.getEmail("testuser2", TEST_LDAPS_CONF));
+ assertEquals(LdapAuth3.getEmail("testuser", TEST_LDAP_CONF), "testuser@example.com");
+ assertEquals(LdapAuth3.getEmail("testuser2", TEST_LDAPS_CONF), "peter@example.org");
assertEquals(null, LdapAuth3.getEmail("non-exsting", TEST_LDAPS_CONF));
}
-
+
@Test
public void gettingUsernameForEmail() throws LDAPException {
- assertEquals("idsTestUser", LdapAuth3.getUsername("testuser@example.com", TEST_LDAP_CONF));
- assertEquals("testuser2", LdapAuth3.getUsername("peter@example.org", TEST_LDAPS_CONF));
+ assertEquals(LdapAuth3.getUsername("testuser@example.com", TEST_LDAP_CONF), "idsTestUser");
+ assertEquals(LdapAuth3.getUsername("peter@example.org", TEST_LDAPS_CONF), "testuser2");
assertEquals(null, LdapAuth3.getUsername("non-exsting", TEST_LDAPS_CONF));
-
- assertEquals("testuser2", LdapAuth3.getUsername("testUser2", TEST_LDAPS_CONF));
+ assertEquals(LdapAuth3.getUsername("testUser2", TEST_LDAPS_CONF), "testuser2");
// login with uid, get idsC2Profile username
- assertEquals("idsTestUser", LdapAuth3.getUsername("testUser", TEST_LDAPS_CONF));
+ assertEquals(LdapAuth3.getUsername("testUser", TEST_LDAPS_CONF), "idsTestUser");
}
@Test
public void gettingMailAttributeForNotRegisteredUserWorks() throws LDAPException {
- assertEquals("not_registered_user@example.com", LdapAuth3.getEmail("not_registered_user", TEST_LDAP_CONF));
+ assertEquals(LdapAuth3.getEmail("not_registered_user", TEST_LDAP_CONF), "not_registered_user@example.com");
}
@Test
public void gettingMailAttributeForBlockedUserWorks() throws LDAPException {
- assertEquals("nameOfBlockedUser@example.com", LdapAuth3.getEmail("nameOfBlockedUser", TEST_LDAP_CONF));
+ assertEquals(LdapAuth3.getEmail("nameOfBlockedUser", TEST_LDAP_CONF), "nameOfBlockedUser@example.com");
}
@Test
public void canLoadLdapConfig() {
LDAPConfig ldapConfig = new LDAPConfig(TEST_LDAPS_CONF);
assertEquals(3269, ldapConfig.port);
- assertEquals("localhost", ldapConfig.host);
+ assertEquals(ldapConfig.host, "localhost");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
index 5389c94..e5b1f38 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/LdapOAuth2Test.java
@@ -1,29 +1,26 @@
package de.ids_mannheim.korap.authentication;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
import java.security.GeneralSecurityException;
-
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.http.entity.ContentType;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
import com.unboundid.ldap.sdk.LDAPException;
-
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.FullConfiguration;
import de.ids_mannheim.korap.constant.AuthenticationMethod;
@@ -43,159 +40,110 @@
@Autowired
private FullConfiguration config;
+
@Autowired
private AccessTokenDao accessDao;
+
@Autowired
private RefreshTokenDao refreshDao;
+
@Autowired
private OAuth2ClientDao clientDao;
-
+
private String testUsername = "idsTestUser";
+
private String testUserEmail = "testuser@example.com";
+
private String redirectUri = "https://client.com/redirect";
- @BeforeClass
- public static void startTestLDAPServer ()
- throws LDAPException, GeneralSecurityException {
+ @BeforeAll
+ static void startTestLDAPServer() throws LDAPException, GeneralSecurityException {
LdapAuth3Test.startDirectoryServer();
-
}
- @AfterClass
- public static void stopTestLDAPServer () {
+ @AfterAll
+ static void stopTestLDAPServer() {
LdapAuth3Test.shutDownDirectoryServer();
}
- @Before
- public void setLDAPAuthentication () {
+ @BeforeEach
+ public void setLDAPAuthentication() {
config.setOAuth2passwordAuthentication(AuthenticationMethod.LDAP);
}
- @After
- public void resetAuthenticationMethod () {
+ @AfterEach
+ public void resetAuthenticationMethod() {
config.setOAuth2passwordAuthentication(AuthenticationMethod.TEST);
}
@Test
- public void testRequestTokenPasswordUnknownUser ()
- throws KustvaktException {
-
- Response response = requestTokenWithPassword(superClientId,
- clientSecret, "unknown", "password");
-
+ public void testRequestTokenPasswordUnknownUser() throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId, clientSecret, "unknown", "password");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2023, node.at("/errors/0/0").asInt());
- assertEquals(
- "LDAP Authentication failed due to unknown user or password!",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "LDAP Authentication failed due to unknown user or password!");
}
@Test
- public void testMapEmailToUsername () throws KustvaktException {
- Response response = requestTokenWithPassword(superClientId,
- clientSecret, testUserEmail, "password");
+ public void testMapEmailToUsername() throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId, clientSecret, testUserEmail, "password");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
-
String accessToken = node.at("/access_token").asText();
AccessToken accessTokenObj = accessDao.retrieveAccessToken(accessToken);
assertEquals(testUsername, accessTokenObj.getUserId());
-
String refreshToken = node.at("/refresh_token").asText();
RefreshToken rt = refreshDao.retrieveRefreshToken(refreshToken);
assertEquals(testUsername, rt.getUserId());
-
testRegisterPublicClient(accessToken);
node = testRegisterConfidentialClient(accessToken);
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
-
testRequestTokenWithAuthorization(clientId, clientSecret, accessToken);
}
-
- private void testRegisterPublicClient (String accessToken)
- throws ProcessingException,
- KustvaktException {
+
+ private void testRegisterPublicClient(String accessToken) throws ProcessingException, KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("LDAP test client");
json.setType(OAuth2ClientType.PUBLIC);
- json.setDescription(
- "Test registering a public client with LDAP authentication");
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("register")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(Entity.json(json));
-
+ json.setDescription("Test registering a public client with LDAP authentication");
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String clientId = node.at("/client_id").asText();
OAuth2Client client = clientDao.retrieveClientById(clientId);
assertEquals(testUsername, client.getRegisteredBy());
}
-
- private JsonNode testRegisterConfidentialClient (String accessToken)
- throws ProcessingException,
- KustvaktException {
+
+ private JsonNode testRegisterConfidentialClient(String accessToken) throws ProcessingException, KustvaktException {
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName("LDAP test client");
json.setType(OAuth2ClientType.CONFIDENTIAL);
json.setRedirectURI(redirectUri);
- json.setDescription(
- "Test registering a confidential client with LDAP authentication");
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("register")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(Entity.json(json));
-
+ json.setDescription("Test registering a confidential client with LDAP authentication");
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String clientId = node.at("/client_id").asText();
OAuth2Client client = clientDao.retrieveClientById(clientId);
assertEquals(testUsername, client.getRegisteredBy());
return node;
}
-
- private void testRequestTokenWithAuthorization (String clientId,
- String clientSecret, String accessToken) throws KustvaktException {
+
+ private void testRequestTokenWithAuthorization(String clientId, String clientSecret, String accessToken) throws KustvaktException {
String authHeader = "Bearer " + accessToken;
- Response response = target().path(API_VERSION).path("oauth2")
- .path("authorize")
- .queryParam("response_type", "code")
- .queryParam("client_id", clientId)
- .queryParam("client_secret", clientSecret)
- .queryParam("scope", "search match_info")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .get();
-
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("oauth2").path("authorize").queryParam("response_type", "code").queryParam("client_id", clientId).queryParam("client_secret", clientSecret).queryParam("scope", "search match_info").request().header(Attributes.AUTHORIZATION, authHeader).get();
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
-
- MultiValueMap<String, String> params = UriComponentsBuilder
- .fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
String code = params.getFirst("code");
-
response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
-
String at = node.at("/access_token").asText();
AccessToken accessTokenObj = accessDao.retrieveAccessToken(at);
assertEquals(testUsername, accessTokenObj.getUserId());
-
String refreshToken = node.at("/refresh_token").asText();
RefreshToken rt = refreshDao.retrieveRefreshToken(refreshToken);
assertEquals(testUsername, rt.getUserId());
diff --git a/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java b/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
index 952f804..c23f168 100644
--- a/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/authentication/RandomCodeGeneratorTest.java
@@ -1,15 +1,14 @@
package de.ids_mannheim.korap.authentication;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.security.NoSuchAlgorithmException;
import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.encryption.RandomCodeGenerator;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -20,18 +19,15 @@
private RandomCodeGenerator random;
@Test
- public void testRandomGenerator ()
- throws NoSuchAlgorithmException, KustvaktException {
+ public void testRandomGenerator() throws NoSuchAlgorithmException, KustvaktException {
String value = random.createRandomCode();
assertEquals(22, value.length());
- //System.out.println(value);
+ // System.out.println(value);
}
- @Ignore
- public void testRandomGeneratorPerformance () throws OAuthSystemException,
- NoSuchAlgorithmException, KustvaktException {
+ @Disabled
+ public void testRandomGeneratorPerformance() throws OAuthSystemException, NoSuchAlgorithmException, KustvaktException {
long min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
-
String code;
while (true) {
long start = System.currentTimeMillis();
@@ -43,20 +39,17 @@
long duration = end - start;
if (duration < min)
min = duration;
- else if (duration > max) max = duration;
- System.out.println(
- "d : " + duration + " min :" + min + ", max: " + max);
-
+ else if (duration > max)
+ max = duration;
+ System.out.println("d : " + duration + " min :" + min + ", max: " + max);
}
}
- @Ignore
- public void testMD5Generator () throws OAuthSystemException,
- NoSuchAlgorithmException, KustvaktException {
+ @Disabled
+ public void testMD5Generator() throws OAuthSystemException, NoSuchAlgorithmException, KustvaktException {
MD5Generator m = new MD5Generator();
String value = m.generateValue();
value = m.generateValue(value);
System.out.println(value);
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java b/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
index 1816a19..8d3d275 100644
--- a/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/cache/NamedVCLoaderTest.java
@@ -1,16 +1,15 @@
package de.ids_mannheim.korap.cache;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.Map;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.collection.DocBits;
import de.ids_mannheim.korap.config.NamedVCLoader;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -23,22 +22,19 @@
@Autowired
private NamedVCLoader vcLoader;
+
@Autowired
private QueryDao dao;
@Test
- public void testNamedVCLoader ()
- throws IOException, QueryException, KustvaktException {
+ public void testNamedVCLoader() throws IOException, QueryException, KustvaktException {
String vcId = "named-vc1";
vcLoader.loadVCToCache(vcId, "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains(vcId));
-
Map<String, DocBits> cachedData = VirtualCorpusCache.retrieve(vcId);
assertTrue(cachedData.size() > 0);
-
VirtualCorpusCache.delete(vcId);
assertFalse(VirtualCorpusCache.contains(vcId));
-
QueryDO vc = dao.retrieveQueryByName(vcId, "system");
assertNotNull(vc);
dao.deleteQuery(vc);
diff --git a/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java b/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
index cd91692..9b63639 100644
--- a/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/cache/TotalResultTest.java
@@ -1,16 +1,14 @@
package de.ids_mannheim.korap.cache;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.core.service.SearchService;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -22,95 +20,46 @@
private SearchService searchService;
@Test
- public void testSearchWithPaging () throws KustvaktException {
-
- assertEquals(0, searchService.getTotalResultCache()
- .getAllCacheElements().size());
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "1").request().get();
+ public void testSearchWithPaging() throws KustvaktException {
+ assertEquals(0, searchService.getTotalResultCache().getAllCacheElements().size());
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "1").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertTrue("totalResults should be a number", node.at("/meta/totalResults").isNumber());
+ assertTrue(node.at("/meta/totalResults").isNumber(), "totalResults should be a number");
int totalResults = node.at("/meta/totalResults").asInt();
-
- assertEquals(1, searchService.getTotalResultCache()
- .getAllCacheElements().size());
-
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "2").request().get();
-
+ assertEquals(1, searchService.getTotalResultCache().getAllCacheElements().size());
+ response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "2").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertTrue("totalResults should be a number", node.at("/meta/totalResults").isNumber());
+ assertTrue(node.at("/meta/totalResults").isNumber(), "totalResults should be a number");
assertEquals(totalResults, node.at("/meta/totalResults").asInt());
-
- assertEquals(1, searchService.getTotalResultCache()
- .getAllCacheElements().size());
-
+ assertEquals(1, searchService.getTotalResultCache().getAllCacheElements().size());
assertTrue(node.at("/meta/cutOff").isMissingNode());
-
testSearchWithCutOff();
}
-
+
@Test
- public void testSearchWithCutOffTrue () throws KustvaktException {
-
- int cacheSize = searchService.getTotalResultCache()
- .getAllCacheElements().size();
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "ich").queryParam("ql", "poliqarp")
- .queryParam("page", "2")
- .queryParam("cutoff", "true")
- .request().get();
+ public void testSearchWithCutOffTrue() throws KustvaktException {
+ int cacheSize = searchService.getTotalResultCache().getAllCacheElements().size();
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "ich").queryParam("ql", "poliqarp").queryParam("page", "2").queryParam("cutoff", "true").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
- String query = "{\"meta\":{\"startPage\":2,\"tokens\":false,\"cutOff\":"
- + "true,\"snippets\":true,\"timeout\":10000},\"query\":{\"@type\":"
- + "\"koral:token\",\"wrap\":{\"@type\":\"koral:term\",\"match\":"
- + "\"match:eq\",\"layer\":\"orth\",\"key\":\"ich\",\"foundry\":"
- + "\"opennlp\",\"rewrites\":[{\"@type\":\"koral:rewrite\",\"src\":"
- + "\"Kustvakt\",\"operation\":\"operation:injection\",\"scope\":"
- + "\"foundry\"}]}},\"@context\":\"http://korap.ids-mannheim.de/ns"
- + "/koral/0.3/context.jsonld\",\"collection\":{\"@type\":\"koral:"
- + "doc\",\"match\":\"match:eq\",\"type\":\"type:regex\",\"value\":"
- + "\"CC-BY.*\",\"key\":\"availability\",\"rewrites\":[{\"@type\":"
- + "\"koral:rewrite\",\"src\":\"Kustvakt\",\"operation\":\"operation:"
- + "insertion\",\"scope\":\"availability(FREE)\"}]}}";
-
+ String query = "{\"meta\":{\"startPage\":2,\"tokens\":false,\"cutOff\":" + "true,\"snippets\":true,\"timeout\":10000},\"query\":{\"@type\":" + "\"koral:token\",\"wrap\":{\"@type\":\"koral:term\",\"match\":" + "\"match:eq\",\"layer\":\"orth\",\"key\":\"ich\",\"foundry\":" + "\"opennlp\",\"rewrites\":[{\"@type\":\"koral:rewrite\",\"src\":" + "\"Kustvakt\",\"operation\":\"operation:injection\",\"scope\":" + "\"foundry\"}]}},\"@context\":\"http://korap.ids-mannheim.de/ns" + "/koral/0.3/context.jsonld\",\"collection\":{\"@type\":\"koral:" + "doc\",\"match\":\"match:eq\",\"type\":\"type:regex\",\"value\":" + "\"CC-BY.*\",\"key\":\"availability\",\"rewrites\":[{\"@type\":" + "\"koral:rewrite\",\"src\":\"Kustvakt\",\"operation\":\"operation:" + "insertion\",\"scope\":\"availability(FREE)\"}]}}";
int cacheKey = searchService.createTotalResultCacheKey(query);
- assertEquals(null, searchService.getTotalResultCache()
- .getCacheValue(cacheKey));
-
- assertEquals(cacheSize, searchService.getTotalResultCache()
- .getAllCacheElements().size());
+ assertEquals(null, searchService.getTotalResultCache().getCacheValue(cacheKey));
+ assertEquals(cacheSize, searchService.getTotalResultCache().getAllCacheElements().size());
}
-
- private void testSearchWithCutOff () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "3").queryParam("cutoff", "false").request()
- .get();
+
+ private void testSearchWithCutOff() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "3").queryParam("cutoff", "false").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertTrue(node.at("/meta/cutOff").isMissingNode());
-
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "4").queryParam("cutoff", "true").request()
- .get();
-
+ response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "4").queryParam("cutoff", "true").request().get();
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
-
assertTrue(node.at("/meta/cutOff").asBoolean());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java b/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
index 525d24b..98fa24b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/LiteJerseyTest.java
@@ -1,12 +1,5 @@
package de.ids_mannheim.korap.config;
-import org.junit.runner.RunWith;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.support.GenericApplicationContext;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
-import org.springframework.web.context.support.GenericWebApplicationContext;
-
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.test.DeploymentContext;
@@ -15,49 +8,42 @@
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.support.GenericApplicationContext;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
+import org.springframework.web.context.support.GenericWebApplicationContext;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config-lite.xml")
-public abstract class LiteJerseyTest extends JerseyTest{
-
+public abstract class LiteJerseyTest extends JerseyTest {
+
public static final String API_VERSION = "v1.0";
-
+
@Autowired
protected GenericApplicationContext applicationContext;
-
- public static String[] classPackages =
- new String[] {
- "de.ids_mannheim.korap.core.web",
- "de.ids_mannheim.korap.web.filter",
- "de.ids_mannheim.korap.web.utils",
- "de.ids_mannheim.korap.test",
- "com.fasterxml.jackson.jaxrs.json"};
-
+
+ public static String[] classPackages = new String[]{"de.ids_mannheim.korap.core.web", "de.ids_mannheim.korap.web.filter", "de.ids_mannheim.korap.web.utils", "de.ids_mannheim.korap.test", "com.fasterxml.jackson.jaxrs.json"};
+
@Override
- protected TestContainerFactory getTestContainerFactory ()
- throws TestContainerException {
+ protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
+ @BeforeEach
@Override
- public void setUp () throws Exception {
-
- GenericWebApplicationContext genericContext =
- new GenericWebApplicationContext();
-
+ public void setUp() throws Exception {
+ GenericWebApplicationContext genericContext = new GenericWebApplicationContext();
genericContext.setParent(this.applicationContext);
genericContext.setClassLoader(this.applicationContext.getClassLoader());
-
StaticContextLoaderListener.applicationContext = genericContext;
super.setUp();
}
-
+
@Override
protected DeploymentContext configureDeployment() {
- return ServletDeploymentContext
- .forServlet(new ServletContainer(new ResourceConfig().packages(classPackages)))
- .addListener(StaticContextLoaderListener.class)
- .contextParam("adminToken", "secret")
- .build();
+ return ServletDeploymentContext.forServlet(new ServletContainer(new ResourceConfig().packages(classPackages))).addListener(StaticContextLoaderListener.class).contextParam("adminToken", "secret").build();
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java b/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
index d393764..1fca983 100644
--- a/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/config/SpringJerseyTest.java
@@ -8,17 +8,18 @@
import org.glassfish.jersey.test.grizzly.GrizzlyWebTestContainerFactory;
import org.glassfish.jersey.test.spi.TestContainerException;
import org.glassfish.jersey.test.spi.TestContainerFactory;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.web.context.support.GenericWebApplicationContext;
@DirtiesContext(classMode = ClassMode.BEFORE_CLASS)
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public abstract class SpringJerseyTest extends JerseyTest {
@@ -27,37 +28,25 @@
@Autowired
protected GenericApplicationContext applicationContext;
- public static String[] classPackages =
- new String[] { "de.ids_mannheim.korap.web",
- "de.ids_mannheim.korap.core.web",
- "de.ids_mannheim.korap.test",
- "com.fasterxml.jackson.jaxrs.json"};
+ public static String[] classPackages = new String[]{"de.ids_mannheim.korap.web", "de.ids_mannheim.korap.core.web", "de.ids_mannheim.korap.test", "com.fasterxml.jackson.jaxrs.json"};
@Override
- protected TestContainerFactory getTestContainerFactory ()
- throws TestContainerException {
+ protected TestContainerFactory getTestContainerFactory() throws TestContainerException {
return new GrizzlyWebTestContainerFactory();
}
+ @BeforeEach
@Override
- public void setUp () throws Exception {
-
- GenericWebApplicationContext genericContext =
- new GenericWebApplicationContext();
-
+ public void setUp() throws Exception {
+ GenericWebApplicationContext genericContext = new GenericWebApplicationContext();
genericContext.setParent(this.applicationContext);
genericContext.setClassLoader(this.applicationContext.getClassLoader());
-
StaticContextLoaderListener.applicationContext = genericContext;
super.setUp();
}
@Override
protected DeploymentContext configureDeployment() {
- return ServletDeploymentContext
- .forServlet(new ServletContainer(new ResourceConfig().packages(classPackages)))
- .addListener(StaticContextLoaderListener.class)
- .contextParam("adminToken", "secret")
- .build();
+ return ServletDeploymentContext.forServlet(new ServletContainer(new ResourceConfig().packages(classPackages))).addListener(StaticContextLoaderListener.class).contextParam("adminToken", "secret").build();
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
index a4d770b..59ca413 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/RolePrivilegeDaoTest.java
@@ -1,87 +1,77 @@
package de.ids_mannheim.korap.dao;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.ids_mannheim.korap.constant.PredefinedRole;
import de.ids_mannheim.korap.constant.PrivilegeType;
import de.ids_mannheim.korap.entity.Privilege;
import de.ids_mannheim.korap.entity.Role;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public class RolePrivilegeDaoTest {
@Autowired
private RoleDao roleDao;
+
@Autowired
private PrivilegeDao privilegeDao;
@Test
- public void retrievePredefinedRole () {
+ public void retrievePredefinedRole() {
Role r = roleDao.retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
assertEquals(1, r.getId());
}
@Test
- public void createDeleteRole () {
+ public void createDeleteRole() {
String roleName = "vc editor";
-
List<PrivilegeType> privileges = new ArrayList<PrivilegeType>();
privileges.add(PrivilegeType.READ);
privileges.add(PrivilegeType.WRITE);
roleDao.createRole(roleName, privileges);
-
Role r = roleDao.retrieveRoleByName(roleName);
assertEquals(roleName, r.getName());
assertEquals(2, r.getPrivileges().size());
-
roleDao.deleteRole(r.getId());
}
@Test
- public void updateRole () {
+ public void updateRole() {
Role role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
roleDao.editRoleName(role.getId(), "USER_GROUP_MEMBER role");
-
role = roleDao.retrieveRoleById(role.getId());
- assertEquals("USER_GROUP_MEMBER role", role.getName());
-
+ assertEquals(role.getName(), "USER_GROUP_MEMBER role");
roleDao.editRoleName(role.getId(), "USER_GROUP_MEMBER");
role = roleDao.retrieveRoleById(role.getId());
- assertEquals("USER_GROUP_MEMBER", role.getName());
+ assertEquals(role.getName(), "USER_GROUP_MEMBER");
}
-
@Test
- public void addDeletePrivilegeOfExistingRole () {
+ public void addDeletePrivilegeOfExistingRole() {
Role role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
List<Privilege> privileges = role.getPrivileges();
assertEquals(1, role.getPrivileges().size());
assertEquals(privileges.get(0).getName(), PrivilegeType.DELETE);
-
// add privilege
List<PrivilegeType> privilegeTypes = new ArrayList<PrivilegeType>();
privilegeTypes.add(PrivilegeType.READ);
privilegeDao.addPrivilegesToRole(role, privilegeTypes);
-
role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
assertEquals(2, role.getPrivileges().size());
-
- //delete privilege
+ // delete privilege
privilegeDao.deletePrivilegeFromRole(role.getId(), PrivilegeType.READ);
-
role = roleDao.retrieveRoleByName("USER_GROUP_MEMBER");
assertEquals(1, role.getPrivileges().size());
assertEquals(privileges.get(0).getName(), PrivilegeType.DELETE);
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
index 25a1b36..dd5fcf5 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupDaoTest.java
@@ -1,18 +1,18 @@
package de.ids_mannheim.korap.dao;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.ids_mannheim.korap.config.FullConfiguration;
import de.ids_mannheim.korap.constant.GroupMemberStatus;
@@ -30,34 +30,34 @@
import de.ids_mannheim.korap.user.User.CorpusAccess;
import edu.emory.mathcs.backport.java.util.Collections;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public class UserGroupDaoTest {
@Autowired
private UserGroupDao userGroupDao;
+
@Autowired
private QueryDao virtualCorpusDao;
+
@Autowired
private RoleDao roleDao;
+
@Autowired
private FullConfiguration config;
@Test
- public void createDeleteNewUserGroup () throws KustvaktException {
+ public void createDeleteNewUserGroup() throws KustvaktException {
String groupName = "test group";
String createdBy = "test class";
// create group
- int groupId = userGroupDao.createGroup(groupName, null, createdBy,
- UserGroupStatus.ACTIVE);
-
+ int groupId = userGroupDao.createGroup(groupName, null, createdBy, UserGroupStatus.ACTIVE);
// retrieve group
UserGroup group = userGroupDao.retrieveGroupById(groupId, true);
assertEquals(groupName, group.getName());
assertEquals(createdBy, group.getCreatedBy());
assertEquals(UserGroupStatus.ACTIVE, group.getStatus());
assertNull(group.getDeletedBy());
-
// group member
List<UserGroupMember> members = group.getMembers();
assertEquals(1, members.size());
@@ -65,95 +65,68 @@
assertEquals(GroupMemberStatus.ACTIVE, m.getStatus());
assertEquals(createdBy, m.getCreatedBy());
assertEquals(createdBy, m.getUserId());
-
// member roles
Set<Role> roles = roleDao.retrieveRoleByGroupMemberId(m.getId());
assertEquals(2, roles.size());
ArrayList<Role> roleList = new ArrayList<>(2);
roleList.addAll(roles);
Collections.sort(roleList);
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.getId(),
- roleList.get(0).getId());
- assertEquals(PredefinedRole.VC_ACCESS_ADMIN.getId(),
- roleList.get(1).getId());
-
- //retrieve VC by group
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.getId(), roleList.get(0).getId());
+ assertEquals(PredefinedRole.VC_ACCESS_ADMIN.getId(), roleList.get(1).getId());
+ // retrieve VC by group
List<QueryDO> vc = virtualCorpusDao.retrieveQueryByGroup(groupId);
assertEquals(0, vc.size());
-
// soft delete group
- userGroupDao.deleteGroup(groupId, createdBy,
- config.isSoftDeleteGroup());
+ userGroupDao.deleteGroup(groupId, createdBy, config.isSoftDeleteGroup());
group = userGroupDao.retrieveGroupById(groupId);
assertEquals(UserGroupStatus.DELETED, group.getStatus());
-
// hard delete
userGroupDao.deleteGroup(groupId, createdBy, false);
-
KustvaktException exception = assertThrows(KustvaktException.class, () -> {
userGroupDao.retrieveGroupById(groupId);
});
-
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- exception.getStatusCode().intValue());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, exception.getStatusCode().intValue());
}
@Test
- public void retrieveGroupWithMembers () throws KustvaktException {
+ public void retrieveGroupWithMembers() throws KustvaktException {
// dory group
- List<UserGroupMember> members =
- userGroupDao.retrieveGroupById(2, true).getMembers();
+ List<UserGroupMember> members = userGroupDao.retrieveGroupById(2, true).getMembers();
assertEquals(4, members.size());
-
UserGroupMember m = members.get(1);
Set<Role> roles = m.getRoles();
assertEquals(2, roles.size());
-
List<Role> sortedRoles = new ArrayList<>(roles);
Collections.sort(sortedRoles);
-
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
- sortedRoles.get(0).getName());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
- sortedRoles.get(1).getName());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), sortedRoles.get(0).getName());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), sortedRoles.get(1).getName());
}
@Test
- public void retrieveGroupByUserId () throws KustvaktException {
+ public void retrieveGroupByUserId() throws KustvaktException {
List<UserGroup> group = userGroupDao.retrieveGroupByUserId("dory");
assertEquals(2, group.size());
-
group = userGroupDao.retrieveGroupByUserId("pearl");
assertEquals(0, group.size());
}
@Test
- public void addVCToGroup () throws KustvaktException {
+ public void addVCToGroup() throws KustvaktException {
// dory group
int groupId = 2;
-
UserGroup group = userGroupDao.retrieveGroupById(groupId);
String createdBy = "dory";
String name = "dory new vc";
- int id = virtualCorpusDao.createQuery(name,
- ResourceType.PROJECT, QueryType.VIRTUAL_CORPUS,
- CorpusAccess.PUB, "corpusSigle=WPD15", "", "", "", false,
- createdBy, null, null);
-
+ int id = virtualCorpusDao.createQuery(name, ResourceType.PROJECT, QueryType.VIRTUAL_CORPUS, CorpusAccess.PUB, "corpusSigle=WPD15", "", "", "", false, createdBy, null, null);
QueryDO virtualCorpus = virtualCorpusDao.retrieveQueryById(id);
- userGroupDao.addQueryToGroup(virtualCorpus, createdBy,
- QueryAccessStatus.ACTIVE, group);
-
+ userGroupDao.addQueryToGroup(virtualCorpus, createdBy, QueryAccessStatus.ACTIVE, group);
List<QueryDO> vc = virtualCorpusDao.retrieveQueryByGroup(groupId);
assertEquals(2, vc.size());
assertEquals(name, vc.get(1).getName());
-
// delete vc from group
userGroupDao.deleteQueryFromGroup(virtualCorpus.getId(), groupId);
-
vc = virtualCorpusDao.retrieveQueryByGroup(groupId);
assertEquals(1, vc.size());
-
// delete vc
virtualCorpusDao.deleteQuery(virtualCorpus);
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
index 8b38d7b..93e3b78 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/UserGroupMemberDaoTest.java
@@ -1,22 +1,22 @@
package de.ids_mannheim.korap.dao;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Set;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.ids_mannheim.korap.constant.PredefinedRole;
import de.ids_mannheim.korap.entity.Role;
import de.ids_mannheim.korap.entity.UserGroupMember;
import de.ids_mannheim.korap.exceptions.KustvaktException;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public class UserGroupMemberDaoTest {
@@ -27,25 +27,22 @@
private RoleDao roleDao;
@Test
- public void testRetrieveMemberByRole () throws KustvaktException {
+ public void testRetrieveMemberByRole() throws KustvaktException {
// dory group
- List<UserGroupMember> vcaAdmins = dao.retrieveMemberByRole(2,
- PredefinedRole.VC_ACCESS_ADMIN.getId());
+ List<UserGroupMember> vcaAdmins = dao.retrieveMemberByRole(2, PredefinedRole.VC_ACCESS_ADMIN.getId());
// System.out.println(vcaAdmins);
assertEquals(1, vcaAdmins.size());
- assertEquals("dory", vcaAdmins.get(0).getUserId());
+ assertEquals(vcaAdmins.get(0).getUserId(), "dory");
}
@Test
- public void testAddSameMemberRole () throws KustvaktException {
+ public void testAddSameMemberRole() throws KustvaktException {
UserGroupMember member = dao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
- Role adminRole = roleDao
- .retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
+ Role adminRole = roleDao.retrieveRoleById(PredefinedRole.USER_GROUP_ADMIN.getId());
roles.add(adminRole);
member.setRoles(roles);
dao.updateMember(member);
-
member = dao.retrieveMemberById("dory", 1);
member.getRoles();
assertEquals(2, roles.size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
index 57bcf81..6be38cf 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusAccessDaoTest.java
@@ -1,21 +1,21 @@
package de.ids_mannheim.korap.dao;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.ids_mannheim.korap.constant.QueryAccessStatus;
import de.ids_mannheim.korap.entity.QueryAccess;
import de.ids_mannheim.korap.entity.UserGroup;
import de.ids_mannheim.korap.exceptions.KustvaktException;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public class VirtualCorpusAccessDaoTest {
@@ -23,14 +23,12 @@
private QueryAccessDao dao;
@Test
- public void getAccessByVC () throws KustvaktException {
+ public void getAccessByVC() throws KustvaktException {
List<QueryAccess> vcaList = dao.retrieveActiveAccessByQuery(2);
QueryAccess access = vcaList.get(0);
assertEquals(QueryAccessStatus.ACTIVE, access.getStatus());
- assertEquals("dory", access.getCreatedBy());
-
+ assertEquals(access.getCreatedBy(), "dory");
UserGroup group = access.getUserGroup();
assertEquals(2, group.getId());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
index 002dbfc..826a687 100644
--- a/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/dao/VirtualCorpusDaoTest.java
@@ -1,15 +1,14 @@
package de.ids_mannheim.korap.dao;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.Iterator;
import java.util.List;
import javax.persistence.PersistenceException;
-import org.hibernate.exception.GenericJDBCException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -26,132 +25,108 @@
private QueryDao dao;
@Test
- public void testListVCByType () throws KustvaktException {
- List<QueryDO> vcList =
- dao.retrieveQueryByType(ResourceType.PUBLISHED, null, QueryType.VIRTUAL_CORPUS);
+ public void testListVCByType() throws KustvaktException {
+ List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.PUBLISHED, null, QueryType.VIRTUAL_CORPUS);
assertEquals(1, vcList.size());
-
QueryDO vc = vcList.get(0);
assertEquals(4, vc.getId());
- assertEquals("published-vc", vc.getName());
- assertEquals("marlin", vc.getCreatedBy());
+ assertEquals(vc.getName(), "published-vc");
+ assertEquals(vc.getCreatedBy(), "marlin");
}
@Test
- public void testSystemVC () throws KustvaktException {
+ public void testSystemVC() throws KustvaktException {
// insert vc
- int id = dao.createQuery("system-vc", ResourceType.SYSTEM,
- QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE,
- "corpusSigle=GOE", "definition", "description", "experimental",
- false, "test class", null, null);
-
+ int id = dao.createQuery("system-vc", ResourceType.SYSTEM, QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE, "corpusSigle=GOE", "definition", "description", "experimental", false, "test class", null, null);
// select vc
- List<QueryDO> vcList =
- dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
+ List<QueryDO> vcList = dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
assertEquals(2, vcList.size());
-
QueryDO vc = dao.retrieveQueryById(id);
// delete vc
dao.deleteQuery(vc);
-
// check if vc has been deleted
- KustvaktException exception =
- assertThrows(KustvaktException.class, () -> {
- dao.retrieveQueryById(id);
- });
-
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- exception.getStatusCode().intValue());
+ KustvaktException exception = assertThrows(KustvaktException.class, () -> {
+ dao.retrieveQueryById(id);
+ });
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, exception.getStatusCode().intValue());
}
@Test
- public void testNonUniqueVC () throws KustvaktException {
-
- PersistenceException exception = assertThrows(PersistenceException.class, ()->{
- dao.createQuery("system-vc", ResourceType.SYSTEM,
- QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE,
- "corpusSigle=GOE", "definition", "description", "experimental",
- false, "system", null, null);
- });
- assertEquals(
- "org.hibernate.exception.GenericJDBCException: could not execute statement",
- exception.getMessage());
+ public void testNonUniqueVC() throws KustvaktException {
+ PersistenceException exception = assertThrows(PersistenceException.class, () -> {
+ dao.createQuery("system-vc", ResourceType.SYSTEM, QueryType.VIRTUAL_CORPUS, User.CorpusAccess.FREE, "corpusSigle=GOE", "definition", "description", "experimental", false, "system", null, null);
+ });
+ assertEquals(exception.getMessage(), "org.hibernate.exception.GenericJDBCException: could not execute statement");
}
@Test
- public void retrieveSystemVC () throws KustvaktException {
- List<QueryDO> vc =
- dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
+ public void retrieveSystemVC() throws KustvaktException {
+ List<QueryDO> vc = dao.retrieveQueryByType(ResourceType.SYSTEM, null, QueryType.VIRTUAL_CORPUS);
assertEquals(1, vc.size());
}
/**
* retrieve private and group VC
- *
+ *
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserDory () throws KustvaktException {
- List<QueryDO> virtualCorpora =
- dao.retrieveQueryByUser("dory", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserDory() throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("dory", QueryType.VIRTUAL_CORPUS);
// System.out.println(virtualCorpora);
assertEquals(4, virtualCorpora.size());
// ordered by id
Iterator<QueryDO> i = virtualCorpora.iterator();
- assertEquals("dory-vc", i.next().getName());
- assertEquals("group-vc", i.next().getName());
- assertEquals("system-vc", i.next().getName());
- assertEquals("published-vc", i.next().getName());
+ assertEquals(i.next().getName(), "dory-vc");
+ assertEquals(i.next().getName(), "group-vc");
+ assertEquals(i.next().getName(), "system-vc");
+ assertEquals(i.next().getName(), "published-vc");
}
/**
* retrieves group VC and
* excludes hidden published VC (user has never used it)
- *
+ *
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserNemo () throws KustvaktException {
- List<QueryDO> virtualCorpora =
- dao.retrieveQueryByUser("nemo", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserNemo() throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("nemo", QueryType.VIRTUAL_CORPUS);
assertEquals(3, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
- assertEquals("group-vc", i.next().getName());
- assertEquals("system-vc", i.next().getName());
- assertEquals("nemo-vc", i.next().getName());
+ assertEquals(i.next().getName(), "group-vc");
+ assertEquals(i.next().getName(), "system-vc");
+ assertEquals(i.next().getName(), "nemo-vc");
}
/**
* retrieves published VC by the owner and
* excludes group vc when a user is a pending member
- *
+ *
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserMarlin () throws KustvaktException {
- List<QueryDO> virtualCorpora =
- dao.retrieveQueryByUser("marlin", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserMarlin() throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("marlin", QueryType.VIRTUAL_CORPUS);
assertEquals(3, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
- assertEquals("system-vc", i.next().getName());
- assertEquals("published-vc", i.next().getName());
- assertEquals("marlin-vc", i.next().getName());
+ assertEquals(i.next().getName(), "system-vc");
+ assertEquals(i.next().getName(), "published-vc");
+ assertEquals(i.next().getName(), "marlin-vc");
}
/**
* retrieves published VC from an auto-generated hidden group and
* excludes group vc when a user is a deleted member
- *
+ *
* @throws KustvaktException
*/
@Test
- public void retrieveVCByUserPearl () throws KustvaktException {
- List<QueryDO> virtualCorpora =
- dao.retrieveQueryByUser("pearl", QueryType.VIRTUAL_CORPUS);
+ public void retrieveVCByUserPearl() throws KustvaktException {
+ List<QueryDO> virtualCorpora = dao.retrieveQueryByUser("pearl", QueryType.VIRTUAL_CORPUS);
assertEquals(2, virtualCorpora.size());
Iterator<QueryDO> i = virtualCorpora.iterator();
- assertEquals("system-vc", i.next().getName());
- assertEquals("published-vc", i.next().getName());
+ assertEquals(i.next().getName(), "system-vc");
+ assertEquals(i.next().getName(), "published-vc");
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
index 37d81a0..a679a12 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/BCryptTest.java
@@ -1,21 +1,19 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.mindrot.jbcrypt.BCrypt;
public class BCryptTest {
@Test
- public void testSalt () {
+ public void testSalt() {
String salt = BCrypt.gensalt(8);
-// System.out.println(salt);
-
+ // System.out.println(salt);
String plain = "secret";
String password = BCrypt.hashpw(plain, salt);
-// System.out.println(password);
-
+ // System.out.println(password);
assertTrue(BCrypt.checkpw(plain, password));
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
index 8e46259..980d749 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/CollectionQueryBuilderTest.java
@@ -1,11 +1,10 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.query.serialize.QuerySerializer;
import de.ids_mannheim.korap.utils.JsonUtils;
@@ -18,350 +17,271 @@
public class CollectionQueryBuilderTest {
@Test
- public void testsimpleAdd () throws KustvaktException {
+ public void testsimpleAdd() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD");
-
JsonNode node = JsonUtils.readTree(b.toJSON());
-
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("corpusSigle", node.at("/collection/key").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "corpusSigle");
}
-
@Test
- public void testSimpleConjunction () throws KustvaktException {
+ public void testSimpleConjunction() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD & textClass=freizeit");
JsonNode node = JsonUtils.readTree(b.toJSON());
-
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
-
- assertEquals("corpusSigle", node.at("/collection/operands/0/key")
- .asText());
- assertEquals("textClass", node.at("/collection/operands/1/key")
- .asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
}
-
@Test
- public void testSimpleDisjunction () throws KustvaktException {
+ public void testSimpleDisjunction() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("corpusSigle=WPD | textClass=freizeit");
JsonNode node = JsonUtils.readTree(b.toJSON());
-
assertNotNull(node);
assert node.at("/collection/operation").asText().equals("operation:or");
- assert node.at("/collection/operands/0/key").asText()
- .equals("corpusSigle");
- assert node.at("/collection/operands/1/key").asText()
- .equals("textClass");
+ assert node.at("/collection/operands/0/key").asText().equals("corpusSigle");
+ assert node.at("/collection/operands/1/key").asText().equals("textClass");
}
-
@Test
- public void testComplexSubQuery () throws KustvaktException {
+ public void testComplexSubQuery() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(corpusSigle=WPD) | (textClass=freizeit & corpusSigle=BRZ13)");
JsonNode node = JsonUtils.readTree(b.toJSON());
-
assertNotNull(node);
assert node.at("/collection/operation").asText().equals("operation:or");
- assert node.at("/collection/operands/0/key").asText()
- .equals("corpusSigle");
- assert node.at("/collection/operands/1/@type").asText()
- .equals("koral:docGroup");
-
+ assert node.at("/collection/operands/0/key").asText().equals("corpusSigle");
+ assert node.at("/collection/operands/1/@type").asText().equals("koral:docGroup");
}
-
@Test
- public void testAddResourceQueryAfter () throws KustvaktException {
+ public void testAddResourceQueryAfter() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(textClass=politik & title=\"random title\") | textClass=wissenschaft");
-
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
c.setBaseQuery(b.toJSON());
c.with("corpusSigle=WPD");
-
JsonNode node = JsonUtils.readTree(c.toJSON());
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/operands/1/@type")
- .asText());
- assertEquals("koral:docGroup", node.at("/collection/operands/0/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
assertEquals(2, node.at("/collection/operands/0/operands").size());
- assertEquals(2, node.at("/collection/operands/0/operands/0/operands")
- .size());
-
- assertEquals("operation:and", node.at("/collection/operation").asText());
- assertEquals("operation:or", node
- .at("/collection/operands/0/operation").asText());
- assertEquals("operation:and",
- node.at("/collection/operands/0/operands/0/operation").asText());
- assertEquals("WPD", node.at("/collection/operands/1/value").asText());
+ assertEquals(2, node.at("/collection/operands/0/operands/0/operands").size());
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/0/operation").asText(), "operation:or");
+ assertEquals(node.at("/collection/operands/0/operands/0/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
}
-
@Test
- public void testAddComplexResourceQueryAfter () throws KustvaktException {
+ public void testAddComplexResourceQueryAfter() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(title=\"random title\") | (textClass=wissenschaft)");
-
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
c.setBaseQuery(b.toJSON());
c.with("(corpusSigle=BRZ13 | corpusSigle=AZPS)");
-
JsonNode node = JsonUtils.readTree(c.toJSON());
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("koral:docGroup", node.at("/collection/operands/1/@type")
- .asText());
- assertEquals("BRZ13", node
- .at("/collection/operands/1/operands/0/value").asText());
- assertEquals("AZPS", node.at("/collection/operands/1/operands/1/value")
- .asText());
- assertEquals("random title",
- node.at("/collection/operands/0/operands/0/value").asText());
- assertEquals("wissenschaft",
- node.at("/collection/operands/0/operands/1/value").asText());
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "BRZ13");
+ assertEquals(node.at("/collection/operands/1/operands/1/value").asText(), "AZPS");
+ assertEquals(node.at("/collection/operands/0/operands/0/value").asText(), "random title");
+ assertEquals(node.at("/collection/operands/0/operands/1/value").asText(), "wissenschaft");
}
-
@Test
- public void testBuildQuery () throws KustvaktException {
+ public void testBuildQuery() throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
check.setCollection(coll);
-
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.setBaseQuery(check.toJSON());
b.with("textClass=freizeit");
-
JsonNode res = (JsonNode) b.rebaseCollection();
assertNotNull(res);
- assertEquals("koral:docGroup", res.at("/collection/@type").asText());
- assertEquals("operation:and", res.at("/collection/operation").asText());
- assertEquals("koral:doc", res.at("/collection/operands/0/@type")
- .asText());
- assertEquals("freizeit", res.at("/collection/operands/1/value")
- .asText());
- assertEquals("textClass", res.at("/collection/operands/1/key").asText());
-
- assertEquals("koral:doc", res.at("/collection/operands/1/@type")
- .asText());
- assertEquals("WPD", res.at("/collection/operands/0/value").asText());
- assertEquals("corpusSigle", res.at("/collection/operands/0/key")
- .asText());
-
+ assertEquals(res.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(res.at("/collection/operation").asText(), "operation:and");
+ assertEquals(res.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(res.at("/collection/operands/1/value").asText(), "freizeit");
+ assertEquals(res.at("/collection/operands/1/key").asText(), "textClass");
+ assertEquals(res.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(res.at("/collection/operands/0/value").asText(), "WPD");
+ assertEquals(res.at("/collection/operands/0/key").asText(), "corpusSigle");
// check also that query is still there
- assertEquals("koral:token", res.at("/query/@type").asText());
- assertEquals("koral:term", res.at("/query/wrap/@type").asText());
- assertEquals("Haus", res.at("/query/wrap/key").asText());
- assertEquals("lemma", res.at("/query/wrap/layer").asText());
+ assertEquals(res.at("/query/@type").asText(), "koral:token");
+ assertEquals(res.at("/query/wrap/@type").asText(), "koral:term");
+ assertEquals(res.at("/query/wrap/key").asText(), "Haus");
+ assertEquals(res.at("/query/wrap/layer").asText(), "lemma");
}
-
@Test
- public void testBaseQueryBuild () throws KustvaktException {
+ public void testBaseQueryBuild() throws KustvaktException {
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.with("(corpusSigle=ADF) | (textClass=freizeit & corpusSigle=WPD)");
-
KoralCollectionQueryBuilder c = new KoralCollectionQueryBuilder();
c.setBaseQuery(b.toJSON());
-
c.with("corpusSigle=BRZ13");
JsonNode base = (JsonNode) c.rebaseCollection();
assertNotNull(base);
assertEquals(base.at("/collection/@type").asText(), "koral:docGroup");
- assertEquals(base.at("/collection/operands/1/@type").asText(),
- "koral:doc");
+ assertEquals(base.at("/collection/operands/1/@type").asText(), "koral:doc");
assertEquals(base.at("/collection/operands/1/value").asText(), "BRZ13");
- assertEquals(base.at("/collection/operands/0/@type").asText(),
- "koral:docGroup");
+ assertEquals(base.at("/collection/operands/0/@type").asText(), "koral:docGroup");
assertEquals(base.at("/collection/operands/0/operands").size(), 2);
}
-
@Test
- public void testNodeMergeWithBase () throws KustvaktException {
+ public void testNodeMergeWithBase() throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
check.setCollection(coll);
-
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.setBaseQuery(check.toJSON());
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
test.with("textClass=wissenschaft | textClass=politik");
JsonNode node = (JsonNode) test.rebaseCollection();
node = b.mergeWith(node);
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
assertEquals(2, node.at("/collection/operands").size());
}
-
@Test
- public void testNodeMergeWithoutBase () throws KustvaktException {
+ public void testNodeMergeWithoutBase() throws KustvaktException {
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
-
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.setBaseQuery(check.toJSON());
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
test.with("corpusSigle=WPD");
-// String json = test.toJSON();
-// System.out.println(json);
- //JsonNode node = (JsonNode) test.rebaseCollection(null);
- //node = b.mergeWith(node);
- //assertNotNull(node);
- //assertEquals("koral:doc", node.at("/collection/@type").asText());
- //assertEquals("corpusSigle", node.at("/collection/key").asText());
+ // String json = test.toJSON();
+ // System.out.println(json);
+ // JsonNode node = (JsonNode) test.rebaseCollection(null);
+ // node = b.mergeWith(node);
+ // assertNotNull(node);
+ // assertEquals("koral:doc", node.at("/collection/@type").asText());
+ // assertEquals("corpusSigle", node.at("/collection/key").asText());
}
-
@Test
- public void testNodeMergeWithoutBaseWrongOperator () throws KustvaktException {
+ public void testNodeMergeWithoutBaseWrongOperator() throws KustvaktException {
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
-
KoralCollectionQueryBuilder b = new KoralCollectionQueryBuilder();
b.setBaseQuery(check.toJSON());
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
// operator is not supposed to be here!
test.and().with("corpusSigle=WPD");
-// String json = test.toJSON();
-// System.out.println(json);
- //JsonNode node = (JsonNode) test.rebaseCollection(null);
- //node = b.mergeWith(node);
- //assertNotNull(node);
- //assertEquals("koral:doc", node.at("/collection/@type").asText());
- //assertEquals("corpusSigle", node.at("/collection/key").asText());
+ // String json = test.toJSON();
+ // System.out.println(json);
+ // JsonNode node = (JsonNode) test.rebaseCollection(null);
+ // node = b.mergeWith(node);
+ // assertNotNull(node);
+ // assertEquals("koral:doc", node.at("/collection/@type").asText());
+ // assertEquals("corpusSigle", node.at("/collection/key").asText());
}
-
@Test
- public void testStoredCollectionBaseQueryBuild () {
-
+ public void testStoredCollectionBaseQueryBuild() {
}
-
@Test
- public void testAddOROperator () throws KustvaktException {
+ public void testAddOROperator() throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
check.setCollection(coll);
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
test.setBaseQuery(check.toJSON());
test.or().with("textClass=wissenschaft | textClass=politik");
JsonNode node = (JsonNode) test.rebaseCollection();
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:or", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:or");
assertEquals(2, node.at("/collection/operands/1/operands").size());
}
-
@Test
- public void testAddANDOperator () throws KustvaktException {
+ public void testAddANDOperator() throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
check.setCollection(coll);
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
test.setBaseQuery(check.toJSON());
test.and().with("textClass=wissenschaft | textClass=politik");
JsonNode node = (JsonNode) test.rebaseCollection();
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
assertEquals(2, node.at("/collection/operands/1/operands").size());
}
-
@Test
- public void testAddDefaultOperator () throws KustvaktException {
+ public void testAddDefaultOperator() throws KustvaktException {
String coll = "corpusSigle=WPD";
String query = "[base=Haus]";
QuerySerializer check = new QuerySerializer();
check.setQuery(query, "poliqarp");
check.setCollection(coll);
-
KoralCollectionQueryBuilder test = new KoralCollectionQueryBuilder();
test.setBaseQuery(check.toJSON());
test.with("textClass=wissenschaft | textClass=politik");
JsonNode node = (JsonNode) test.rebaseCollection();
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
assertEquals(2, node.at("/collection/operands/1/operands").size());
}
@Test
- public void testBaseCollectionNull () throws KustvaktException {
+ public void testBaseCollectionNull() throws KustvaktException {
// base is missing collection segment
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
-
KoralCollectionQueryBuilder total = new KoralCollectionQueryBuilder();
total.setBaseQuery(s.toJSON());
-
KoralCollectionQueryBuilder builder = new KoralCollectionQueryBuilder();
builder.with("textClass=politik & corpusSigle=WPD");
- JsonNode node = total.and().mergeWith(
- (JsonNode) builder.rebaseCollection());
-
+ JsonNode node = total.and().mergeWith((JsonNode) builder.rebaseCollection());
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
- assertEquals("koral:doc", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("koral:doc", node.at("/collection/operands/1/@type")
- .asText());
- assertEquals("textClass", node.at("/collection/operands/0/key")
- .asText());
- assertEquals("corpusSigle", node.at("/collection/operands/1/key")
- .asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
}
-
@Test
- public void testMergeCollectionNull () throws KustvaktException {
+ public void testMergeCollectionNull() throws KustvaktException {
// merge json is missing collection segment
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
s.setCollection("textClass=wissenschaft");
-
KoralCollectionQueryBuilder total = new KoralCollectionQueryBuilder();
total.setBaseQuery(s.toJSON());
-
KoralCollectionQueryBuilder builder = new KoralCollectionQueryBuilder();
- JsonNode node = total.and().mergeWith(
- (JsonNode) builder.rebaseCollection());
+ JsonNode node = total.and().mergeWith((JsonNode) builder.rebaseCollection());
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("textClass", node.at("/collection/key").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "textClass");
}
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
index ffe1c51..7fa7e33 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/ConfigTest.java
@@ -1,23 +1,22 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.config.ConfigLoader;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.utils.ServiceInfo;
import de.ids_mannheim.korap.utils.TimeUtils;
-/**
+/**
* @author hanl
* @date 02/09/2015
*/
@@ -27,34 +26,28 @@
KustvaktConfiguration config;
@Test
- public void testConfigLoader () {
+ public void testConfigLoader() {
InputStream stream = ConfigLoader.loadConfigStream("kustvakt.conf");
assertNotNull(stream);
}
-
@Test
- public void testPropertyLoader () throws IOException {
+ public void testPropertyLoader() throws IOException {
Properties p = ConfigLoader.loadProperties("kustvakt.conf");
assertNotNull(p);
}
@Test
- public void testServiceInfo () {
+ public void testServiceInfo() {
String version = ServiceInfo.getInfo().getVersion();
String name = ServiceInfo.getInfo().getName();
- assertNotEquals("wrong version", "UNKNOWN", version);
- assertNotEquals("wrong name", "UNKNOWN", name);
+ assertNotEquals("UNKNOWN", version, "wrong version");
+ assertNotEquals("UNKNOWN", name, "wrong name");
}
-
@Test
- public void testProperties () {
- assertEquals("token layer does not match", "opennlp", config.getDefault_orthography());
- assertEquals("token expiration does not match",
- TimeUtils.convertTimeToSeconds("1D"), config.getLongTokenTTL());
+ public void testProperties() {
+ assertEquals("opennlp", config.getDefault_orthography(), "token layer does not match");
+ assertEquals(TimeUtils.convertTimeToSeconds("1D"), config.getLongTokenTTL(), "token expiration does not match");
}
-
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
index c4fbbef..7e974f3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/KoralNodeTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
-import org.junit.Test;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ObjectNode;
-
import de.ids_mannheim.korap.rewrite.KoralNode;
import de.ids_mannheim.korap.utils.JsonUtils;
@@ -17,38 +16,33 @@
// todo: 21.10.15 --> e.g. injection does not tell you if an entire node was injected, or just a value!
@Test
- public void addToNode () {
+ public void addToNode() {
ObjectNode node = JsonUtils.createObjectNode();
KoralNode knode = KoralNode.wrapNode(node);
knode.put("value_1", "setting_1");
-
- assertEquals("{\"value_1\":\"setting_1\"}",knode.rawNode().toString());
+ assertEquals(knode.rawNode().toString(), "{\"value_1\":\"setting_1\"}");
}
-
@Test
- public void removeFromNode () {
+ public void removeFromNode() {
ObjectNode node = JsonUtils.createObjectNode();
node.put("value_1", "setting_1");
KoralNode knode = KoralNode.wrapNode(node);
knode.remove("value_1", null);
- assertEquals("{}",knode.rawNode().toString());
+ assertEquals(knode.rawNode().toString(), "{}");
}
-
@Test
- public void replaceObject () {
+ public void replaceObject() {
ObjectNode node = JsonUtils.createObjectNode();
node.put("value_1", "setting_1");
KoralNode knode = KoralNode.wrapNode(node);
knode.replace("value_1", "settings_2", null);
- assertEquals("{\"value_1\":\"settings_2\"}",knode.rawNode().toString());
+ assertEquals(knode.rawNode().toString(), "{\"value_1\":\"settings_2\"}");
}
-
// todo: 21.10.15 --> if a node is injected, that node must contain a "rewrites" reference?!
@Test
- public void addNodeToKoral () {
-
+ public void addNodeToKoral() {
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
index ab5039e..e37f5d2 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/LocalQueryTest.java
@@ -1,13 +1,12 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertNotNull;
+
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
-
import javax.annotation.PostConstruct;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.KrillCollection;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -29,18 +28,16 @@
KustvaktConfiguration config;
@PostConstruct
- public void setup () throws Exception {
+ public void setup() throws Exception {
index = config.getIndexDir();
}
-
@Test
- public void testQuery () throws KustvaktException {
+ public void testQuery() throws KustvaktException {
String qstring = "creationDate since 1786 & creationDate until 1788";
- // qstring = "creationDate since 1765 & creationDate until 1768";
- // qstring = "textType = Aphorismus";
- // qstring = "title ~ \"Werther\"";
-
+ // qstring = "creationDate since 1765 & creationDate until 1768";
+ // qstring = "textType = Aphorismus";
+ // qstring = "title ~ \"Werther\"";
SearchKrill krill = new SearchKrill(index);
KoralCollectionQueryBuilder coll = new KoralCollectionQueryBuilder();
coll.with(qstring);
@@ -48,13 +45,11 @@
assert stats != null && !stats.isEmpty() && !stats.equals("null");
}
-
@Test
- public void testCollQuery () throws IOException, KustvaktException {
+ public void testCollQuery() throws IOException, KustvaktException {
String qstring = "creationDate since 1800 & creationDate until 1820";
CollectionQueryProcessor processor = new CollectionQueryProcessor();
processor.process(qstring);
-
String s = JsonUtils.toJSON(processor.getRequestMap());
KrillCollection c = new KrillCollection(s);
c.setIndex(new SearchKrill(index).getIndex());
@@ -62,9 +57,8 @@
assert docs > 0 && docs < 15;
}
-
@Test
- public void testCollQuery2 () throws IOException {
+ public void testCollQuery2() throws IOException {
String query = "{\"@context\":\"http://korap.ids-mannheim.de/ns/koral/0.3/context.jsonld\",\"errors\":[],\"warnings\":[],\"messages\":[],\"collection\":{\"@type\":\"koral:docGroup\",\"operation\":\"operation:and\",\"operands\":[{\"@type\":\"koral:doc\",\"key\":\"creationDate\",\"type\":\"type:date\",\"value\":\"1786\",\"match\":\"match:geq\"},{\"@type\":\"koral:doc\",\"key\":\"creationDate\",\"type\":\"type:date\",\"value\":\"1788\",\"match\":\"match:leq\"}]},\"query\":{},\"meta\":{}}";
KrillCollection c = new KrillCollection(query);
c.setIndex(new SearchKrill(index).getIndex());
@@ -73,5 +67,4 @@
assertNotNull(sent);
assertNotNull(docs);
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
index f302f31..cca0f47 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/MapUtilsTest.java
@@ -1,14 +1,12 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Map;
-
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import de.ids_mannheim.korap.web.utils.MapUtils;
import edu.emory.mathcs.backport.java.util.Arrays;
@@ -16,27 +14,25 @@
@SuppressWarnings("unchecked")
@Test
- public void testConvertToMap () {
+ public void testConvertToMap() {
MultivaluedMap<String, String> mm = new MultivaluedHashMap<String, String>();
- mm.put("k1", Arrays.asList(new String[] { "a", "b", "c" }));
- mm.put("k2", Arrays.asList(new String[] { "d", "e", "f" }));
-
+ mm.put("k1", Arrays.asList(new String[]{"a", "b", "c"}));
+ mm.put("k2", Arrays.asList(new String[]{"d", "e", "f"}));
Map<String, String> map = MapUtils.toMap(mm);
- assertEquals("a b c", map.get("k1"));
- assertEquals("d e f", map.get("k2"));
+ assertEquals(map.get("k1"), "a b c");
+ assertEquals(map.get("k2"), "d e f");
}
@Test
- public void testConvertNullMap () {
+ public void testConvertNullMap() {
Map<String, String> map = MapUtils.toMap(null);
assertEquals(0, map.size());
}
@Test
- public void testConvertEmptyMap () {
+ public void testConvertEmptyMap() {
MultivaluedMap<String, String> mm = new MultivaluedHashMap<String, String>();
Map<String, String> map = MapUtils.toMap(mm);
assertEquals(0, map.size());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
index d00f6bb..c6328c3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/MetaQueryBuilderTest.java
@@ -1,28 +1,26 @@
package de.ids_mannheim.korap.misc;
+
import de.ids_mannheim.korap.config.QueryBuilderUtil;
import de.ids_mannheim.korap.query.serialize.MetaQueryBuilder;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import java.util.Map;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
/**
* Created by hanl on 17.04.16.
*/
public class MetaQueryBuilderTest {
-
-
@Test
- public void testSpanContext () {
- MetaQueryBuilder m = QueryBuilderUtil.defaultMetaBuilder(0, 1, 5,
- "sentence", false);
+ public void testSpanContext() {
+ MetaQueryBuilder m = QueryBuilderUtil.defaultMetaBuilder(0, 1, 5, "sentence", false);
Map<?, ?> map = m.raw();
- assertEquals("sentence", map.get("context"));
+ assertEquals(map.get("context"), "sentence");
assertEquals(1, map.get("startPage"));
assertEquals(0, map.get("startIndex"));
assertEquals(false, map.get("cutOff"));
-
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
index 8bb0ecd..518ae39 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/RegexTest.java
@@ -1,22 +1,20 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.regex.Matcher;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import de.ids_mannheim.korap.annotation.AnnotationParser;
public class RegexTest {
@Test
- public void testQuote(){
+ public void testQuote() {
String s = "ah[\"-\"]";
Matcher m = AnnotationParser.quotePattern.matcher(s);
- if (m.find()){
- assertEquals("-",m.group(1));
+ if (m.find()) {
+ assertEquals(m.group(1), "-");
}
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
index 18f1cd1..4d82706 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/ScopesTest.java
@@ -1,5 +1,6 @@
package de.ids_mannheim.korap.misc;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Test;
/**
* @author hanl
@@ -8,13 +9,10 @@
public class ScopesTest {
@Test
- public void testScopes () {
-
+ public void testScopes() {
}
-
@Test
- public void testOpenIDScopes () {
-
+ public void testOpenIDScopes() {
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
index 0d2a912..7471e12 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/SerializationTest.java
@@ -1,24 +1,23 @@
package de.ids_mannheim.korap.misc;
-import org.junit.Ignore;
-import org.junit.Test;
+
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
/**
* @author hanl
* @date 21/01/2016
*/
-@Ignore
+@Disabled
public class SerializationTest {
@Test
- public void testSettingsObject () {
-// String t = "poliqarp_test";
-
- // UserSettings s = new UserSettings();
- // Map map = s.toObjectMap();
- // map.put(Attributes.QUERY_LANGUAGE, t);
- // s.updateObjectSettings(map);
- //
- // assert s.getQueryLanguage().equals(t);
-
+ public void testSettingsObject() {
+ // String t = "poliqarp_test";
+ // UserSettings s = new UserSettings();
+ // Map map = s.toObjectMap();
+ // map.put(Attributes.QUERY_LANGUAGE, t);
+ // s.updateObjectSettings(map);
+ //
+ // assert s.getQueryLanguage().equals(t);
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/ServiceSuite.java b/full/src/test/java/de/ids_mannheim/korap/misc/ServiceSuite.java
index 662b96a..ac2c8a1 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/ServiceSuite.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/ServiceSuite.java
@@ -1,11 +1,7 @@
package de.ids_mannheim.korap.misc;
-import org.junit.runner.RunWith;
-import org.junit.runners.Suite;
/**
* @author hanl
* @date 29/02/2016
*/
-@RunWith(Suite.class)
-@Suite.SuiteClasses({ ConfigTest.class })
public class ServiceSuite {}
diff --git a/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java b/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
index a2c8ea6..657ba0b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/misc/StringUtilsTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.misc;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.commons.codec.binary.Base64;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import de.ids_mannheim.korap.authentication.http.AuthorizationData;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.authentication.http.TransferEncoding;
@@ -16,29 +15,23 @@
*/
public class StringUtilsTest {
-
@Test
- public void testTextIToDoc () {
+ public void testTextIToDoc() {
String textSigle = "WPD_AAA.02439";
String docSigle = "WPD_AAA";
assertEquals(docSigle, StringUtils.getDocSigle(textSigle));
assertEquals(docSigle, StringUtils.getDocSigle(docSigle));
}
-
@Test
- public void testBasicHttpSplit () throws KustvaktException {
+ public void testBasicHttpSplit() throws KustvaktException {
String s2 = new String(Base64.encodeBase64("test:testPass".getBytes()));
String[] f2 = TransferEncoding.decodeBase64(s2);
- assertEquals("test", f2[0]);
- assertEquals("testPass", f2[1]);
-
-
+ assertEquals(f2[0], "test");
+ assertEquals(f2[1], "testPass");
HttpAuthorizationHandler handler = new HttpAuthorizationHandler();
- String s1 = "basic "
- + new String(Base64.encodeBase64("test:testPass".getBytes()));
+ String s1 = "basic " + new String(Base64.encodeBase64("test:testPass".getBytes()));
AuthorizationData f1 = handler.parseAuthorizationHeaderValue(s1);
assertEquals(s2, f1.getToken());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
index e820f28..ae8e39b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/CollectionRewriteTest.java
@@ -1,13 +1,11 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.config.TestVariables;
@@ -24,75 +22,56 @@
@Autowired
public KustvaktConfiguration config;
-
+
@Test
- public void testCollectionNodeRemoveCorpusIdNoErrors ()
- throws KustvaktException {
+ public void testCollectionNodeRemoveCorpusIdNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("textClass=politik & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(1, node.at("/collection/operands").size());
}
-
@Test
- public void testCollectionNodeDeletionNotification () {
-
+ public void testCollectionNodeDeletionNotification() {
}
-
@Test
- public void testCollectionNodeRemoveAllCorpusIdNoErrors ()
- throws KustvaktException {
+ public void testCollectionNodeRemoveAllCorpusIdNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("corpusSigle=BRZ13 & corpusSigle=WPD");
String result = s.toJSON();
-
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
-
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(0, node.at("/collection/operands").size());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testCollectionNodeRemoveGroupedCorpusIdNoErrors ()
- throws KustvaktException {
+ public void testCollectionNodeRemoveGroupedCorpusIdNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ13 & textClass=Wissenschaft) & corpusSigle=WPD");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
-
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("textClass",
- node.at("/collection/operands/0/operands/0/key").asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/operands/0/key").asText(), "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
- //fixme: will probably fail when one doc groups are being refactored
+ // fixme: will probably fail when one doc groups are being refactored
@Test
- public void testCollectionCleanEmptyDocGroupNoErrors ()
- throws KustvaktException {
+ public void testCollectionCleanEmptyDocGroupNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
@@ -100,26 +79,17 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft & textClass=Sport");
String result = s.toJSON();
-
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
-
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
-
- assertEquals("textClass", node.at("/collection/operands/0/key")
- .asText());
- assertEquals("textClass", node.at("/collection/operands/1/key")
- .asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testCollectionCleanMoveOneDocFromGroupUpNoErrors ()
- throws KustvaktException {
+ public void testCollectionCleanMoveOneDocFromGroupUpNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
@@ -127,20 +97,16 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ13 & textClass=wissenschaft)");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("textClass", node.at("/collection/key").asText());
- assertEquals("wissenschaft", node.at("/collection/value").asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "textClass");
+ assertEquals(node.at("/collection/value").asText(), "wissenschaft");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testCollectionCleanEmptyGroupAndMoveOneFromGroupUpNoErrors ()
- throws KustvaktException {
+ public void testCollectionCleanEmptyGroupAndMoveOneFromGroupUpNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
@@ -148,20 +114,15 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ13 & corpusSigle=WPD) & textClass=Wissenschaft");
String result = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(result,
- User.UserFactory.getUser("test_user")));
-
+ JsonNode node = JsonUtils.readTree(handler.processQuery(result, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("textClass", node.at("/collection/key").asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testCollectionRemoveAndMoveOneFromGroupUpNoErrors ()
- throws KustvaktException {
+ public void testCollectionRemoveAndMoveOneFromGroupUpNoErrors() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
handler.add(CollectionCleanRewrite.class);
@@ -169,99 +130,71 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(docID=random & textClass=Wissenschaft) & corpusSigle=WPD");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals("koral:doc", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("koral:doc", node.at("/collection/operands/1/@type")
- .asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testPublicCollectionRewriteEmptyAdd () throws KustvaktException {
+ public void testPublicCollectionRewriteEmptyAdd() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionRewrite.class);
-
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("availability", node.at("/collection/key")
- .asText());
- assertEquals("CC-BY.*", node.at("/collection/value")
- .asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
- assertEquals("availability(FREE)", node.at("/collection/rewrites/0/scope")
- .asText());
- //todo:
+ assertEquals(node.at("/collection/key").asText(), "availability");
+ assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ // todo:
}
-
@Test
- public void testPublicCollectionRewriteNonEmptyAdd ()
- throws KustvaktException {
+ public void testPublicCollectionRewriteNonEmptyAdd() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionRewrite.class);
-
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(docSigle=WPD_AAA & textClass=wissenschaft)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
assertNotNull(node);
assertEquals(2, node.at("/collection/operands").size());
- assertEquals("availability",
- node.at("/collection/operands/0/key").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("docSigle",
- node.at("/collection/operands/1/operands/0/key").asText());
- assertEquals("textClass",
- node.at("/collection/operands/1/operands/1/key").asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
- assertEquals("availability(FREE)", node.at("/collection/rewrites/0/scope")
- .asText());
+ assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/key").asText(), "docSigle");
+ assertEquals(node.at("/collection/operands/1/operands/1/key").asText(), "textClass");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
}
-
@Test
- public void testRemoveCorpusFromDifferentGroups () throws KustvaktException {
+ public void testRemoveCorpusFromDifferentGroups() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
QuerySerializer s = new QuerySerializer();
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals("koral:docGroup", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("koral:docGroup", node.at("/collection/operands/1/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:docGroup");
assertEquals(1, node.at("/collection/operands/0/operands").size());
assertEquals(1, node.at("/collection/operands/1/operands").size());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testRemoveOneCorpusAndMoveDocFromTwoGroups ()
- throws KustvaktException {
+ public void testRemoveOneCorpusAndMoveDocFromTwoGroups() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
handler.add(CollectionConstraint.class);
// todo: use this collection query also to test clean up filter! after reduction of corpusSigle (wiss | freizeit)!
@@ -270,29 +203,17 @@
s.setQuery(TestVariables.SIMPLE_ADD_QUERY, "poliqarp");
s.setCollection("(corpusSigle=BRZ14 & textClass=wissenschaft) | (corpusSigle=AZPR | textClass=freizeit)");
String org = s.toJSON();
- JsonNode node = JsonUtils.readTree(handler.processQuery(org,
- User.UserFactory.getUser("test_user")));
+ JsonNode node = JsonUtils.readTree(handler.processQuery(org, User.UserFactory.getUser("test_user")));
assertNotNull(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals("koral:doc", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("koral:doc", node.at("/collection/operands/0/@type")
- .asText());
- assertEquals("textClass", node.at("/collection/operands/0/key")
- .asText());
- assertEquals("wissenschaft", node.at("/collection/operands/0/value")
- .asText());
- assertEquals("koral:doc", node.at("/collection/operands/1/@type")
- .asText());
- assertEquals("textClass", node.at("/collection/operands/1/key")
- .asText());
- assertEquals("freizeit", node.at("/collection/operands/1/value")
- .asText());
- assertEquals("koral:rewrite", node.at("/collection/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "wissenschaft");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "freizeit");
+ assertEquals(node.at("/collection/rewrites/0/@type").asText(), "koral:rewrite");
}
-
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
index 677201c..c079a25 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/FoundryRewriteTest.java
@@ -1,17 +1,17 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -28,92 +28,68 @@
* @author hanl, margaretha
* @date 18/06/2015
*/
-//MH todo: check position and information of rewrites!
+// MH todo: check position and information of rewrites!
public class FoundryRewriteTest extends SpringJerseyTest {
-// private static String simple_add_query = "[pos=ADJA]";
-// private static String simple_rewrite_query = "[base=Haus]";
-// private static String complex_rewrite_query = "<c=INFC>";
-// private static String complex_rewrite_query2 = "[orth=laufe/i & base!=Lauf]";
-// private static String complex_rewrite_query3 = "[(base=laufen | base=gehen) & tt/pos=VVFIN]";
-
+ // private static String simple_add_query = "[pos=ADJA]";
+ // private static String simple_rewrite_query = "[base=Haus]";
+ // private static String complex_rewrite_query = "<c=INFC>";
+ // private static String complex_rewrite_query2 = "[orth=laufe/i & base!=Lauf]";
+ // private static String complex_rewrite_query3 = "[(base=laufen | base=gehen) & tt/pos=VVFIN]";
@Autowired
public KustvaktConfiguration config;
+
@Autowired
- public RewriteHandler handler;
+ public RewriteHandler handler;
+
@Autowired
private LayerMapper m;
-
+
@Test
- public void testSearchRewriteFoundryWithUserSetting () throws KustvaktException {
+ public void testSearchRewriteFoundryWithUserSetting() throws KustvaktException {
// create user setting
String json = "{\"pos-foundry\":\"opennlp\"}";
String username = "foundryRewriteTest";
String pathUsername = "~" + username;
- Response response = target().path(API_VERSION)
- .path(pathUsername).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path(pathUsername).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
// search
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .accept(MediaType.APPLICATION_JSON).get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("search").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).accept(MediaType.APPLICATION_JSON).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
- assertEquals("foundry",
- node.at("/query/wrap/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
}
@Test
- public void testRewritePosFoundryWithUserSetting ()
- throws KustvaktException {
+ public void testRewritePosFoundryWithUserSetting() throws KustvaktException {
// EM: see
// full/src/main/resources/db/insert/V3.6__insert_default_settings.sql
-
String username = "bubbles";
QuerySerializer s = new QuerySerializer();
s.setQuery("[pos=ADJA]", "poliqarp");
- String result =
- handler.processQuery(s.toJSON(), new KorAPUser(username));
+ String result = handler.processQuery(s.toJSON(), new KorAPUser(username));
JsonNode node = JsonUtils.readTree(result);
- assertEquals("corenlp", node.at("/query/wrap/foundry").asText());
- assertEquals("foundry",
- node.at("/query/wrap/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/query/wrap/foundry").asText(), "corenlp");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
}
@Test
- public void testRewriteLemmaFoundryWithUserSetting ()
- throws KustvaktException {
+ public void testRewriteLemmaFoundryWithUserSetting() throws KustvaktException {
String username = "bubbles";
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
- String result =
- handler.processQuery(s.toJSON(), new KorAPUser(username));
+ String result = handler.processQuery(s.toJSON(), new KorAPUser(username));
JsonNode node = JsonUtils.readTree(result);
// EM: only for testing, in fact, opennlp lemma does not
// exist!
- assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
- assertEquals("foundry",
- node.at("/query/wrap/rewrites/0/scope").asText());
+ assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
+ assertEquals(node.at("/query/wrap/rewrites/0/scope").asText(), "foundry");
}
-
-
+
@Test
- public void testDefaultLayerMapperThrowsNoException () {
+ public void testDefaultLayerMapperThrowsNoException() {
assertEquals(config.getDefault_lemma(), m.findFoundry("lemma"));
assertEquals(config.getDefault_pos(), m.findFoundry("pos"));
assertEquals(config.getDefault_orthography(), m.findFoundry("surface"));
@@ -122,75 +98,57 @@
}
@Test
- public void testDefaultFoundryInjectLemmaThrowsNoError ()
- throws KustvaktException {
-
+ public void testDefaultFoundryInjectLemmaThrowsNoError() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
assertFalse(node.at("/query/wrap/foundry").isMissingNode());
- assertEquals(config.getDefault_lemma(), node.at("/query/wrap/foundry")
- .asText());
- assertEquals("lemma", node.at("/query/wrap/layer").asText());
+ assertEquals(config.getDefault_lemma(), node.at("/query/wrap/foundry").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "lemma");
assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
- assertEquals("koral:rewrite", node.at("/query/wrap/rewrites/0/@type")
- .asText());
+ assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(), "koral:rewrite");
}
-
@Test
- public void testDefaultFoundryInjectPOSNoErrors () throws KustvaktException {
-
+ public void testDefaultFoundryInjectPOSNoErrors() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[pos=ADJA]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
-
assertNotNull(node);
assertFalse(node.at("/query/wrap/foundry").isMissingNode());
- assertEquals(config.getDefault_pos(), node.at("/query/wrap/foundry")
- .asText());
- assertEquals("pos", node.at("/query/wrap/layer").asText());
+ assertEquals(config.getDefault_pos(), node.at("/query/wrap/foundry").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "pos");
assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
- assertEquals("koral:rewrite", node.at("/query/wrap/rewrites/0/@type")
- .asText());
-
+ assertEquals(node.at("/query/wrap/rewrites/0/@type").asText(), "koral:rewrite");
}
-
- @Test
- public void testFoundryInjectJoinedQueryNoErrors ()
- throws KustvaktException {
+ @Test
+ public void testFoundryInjectJoinedQueryNoErrors() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=laufe/i & base!=Lauf]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
-
assertNotNull(node);
- assertEquals("koral:termGroup", node.at("/query/wrap/@type").asText());
+ assertEquals(node.at("/query/wrap/@type").asText(), "koral:termGroup");
assertFalse(node.at("/query/wrap/operands/0/foundry").isMissingNode());
assertFalse(node.at("/query/wrap/operands/0/rewrites").isMissingNode());
assertFalse(node.at("/query/wrap/operands/1/foundry").isMissingNode());
assertFalse(node.at("/query/wrap/operands/1/rewrites").isMissingNode());
}
-
@Test
- public void testFoundryInjectGroupedQueryNoErrors ()
- throws KustvaktException {
+ public void testFoundryInjectGroupedQueryNoErrors() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[(base=laufen | tt/pos=VVFIN)]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
-
assertNotNull(node);
- assertEquals("koral:termGroup", node.at("/query/wrap/@type").asText());
- assertFalse(node.at("/query/wrap/operands/0/foundry")
- .isMissingNode());
- assertFalse(node.at("/query/wrap/operands/0/rewrites")
- .isMissingNode());
+ assertEquals(node.at("/query/wrap/@type").asText(), "koral:termGroup");
+ assertFalse(node.at("/query/wrap/operands/0/foundry").isMissingNode());
+ assertFalse(node.at("/query/wrap/operands/0/rewrites").isMissingNode());
assertFalse(node.at("/query/wrap/operands/1/foundry").isMissingNode());
assertTrue(node.at("/query/wrap/operands/1/rewrites").isMissingNode());
}
@@ -201,12 +159,8 @@
s.setQuery("[orth=laufen]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser("test"));
JsonNode node = JsonUtils.readTree(result);
-
- assertEquals("koral:term", node.at("/query/wrap/@type").asText());
- assertFalse(node.at("/query/wrap/foundry")
- .isMissingNode());
- assertFalse(node.at("/query/wrap/rewrites")
- .isMissingNode());
+ assertEquals(node.at("/query/wrap/@type").asText(), "koral:term");
+ assertFalse(node.at("/query/wrap/foundry").isMissingNode());
+ assertFalse(node.at("/query/wrap/rewrites").isMissingNode());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
index 8f45dc9..b0fc1ea 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/IdRewriteTest.java
@@ -1,14 +1,12 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -26,29 +24,24 @@
@Autowired
private KustvaktConfiguration config;
-
+
@Test
- public void insertTokenId () throws KustvaktException {
+ public void insertTokenId() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(IdWriter.class));
-
String query = "[surface=Wort]";
QuerySerializer s = new QuerySerializer();
s.setQuery(query, "poliqarp");
-
String value = handler.processQuery(s.toJSON(), new KorAPUser());
JsonNode result = JsonUtils.readTree(value);
-
assertNotNull(result);
assertTrue(result.path("query").has("idn"));
}
-
@Test
- public void testIdWriterTest () throws KustvaktException {
+ public void testIdWriterTest() throws KustvaktException {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(IdWriter.class));
-
QuerySerializer s = new QuerySerializer();
s.setQuery("[base=Haus]", "poliqarp");
String result = handler.processQuery(s.toJSON(), new KorAPUser());
@@ -57,6 +50,4 @@
assertFalse(node.at("/query/wrap").isMissingNode());
assertFalse(node.at("/query/idn").isMissingNode());
}
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
index 130741d..dcaadbc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/QueryRewriteTest.java
@@ -1,10 +1,10 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
@@ -15,61 +15,32 @@
/**
* @author diewald
- *
*/
public class QueryRewriteTest extends SpringJerseyTest {
@Test
- public void testRewriteRefNotFound ()
- throws KustvaktException, Exception {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "{q}")
- .queryParam("ql", "poliqarp")
- .resolveTemplate("q", "[orth=der]{#examplequery} Baum")
- .request()
- .get();
-
+ public void testRewriteRefNotFound() throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#examplequery} Baum").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals("Query system/examplequery is not found.",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Query system/examplequery is not found.");
}
-
+
@Test
- public void testRewriteSystemQuery ()
- throws KustvaktException, Exception {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "{q}")
- .queryParam("ql", "poliqarp")
- .resolveTemplate("q", "[orth=der]{#system-q} Baum")
- .request()
- .get();
-
+ public void testRewriteSystemQuery() throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#system-q} Baum").request().get();
String ent = response.readEntity(String.class);
-// System.out.println(ent);
+ // System.out.println(ent);
JsonNode node = JsonUtils.readTree(ent);
}
@Test
- public void testRewriteRefRewrite ()
- throws KustvaktException, Exception {
-
+ public void testRewriteRefRewrite() throws KustvaktException, Exception {
// Added in the database migration sql for tests
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "{q}")
- .queryParam("ql", "poliqarp")
- .resolveTemplate("q", "[orth=der]{#dory/dory-q} Baum")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "{q}").queryParam("ql", "poliqarp").resolveTemplate("q", "[orth=der]{#dory/dory-q} Baum").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals("koral:token", node.at("/query/operands/1/@type").asText());
- assertEquals("@type(koral:queryRef)",
- node.at("/query/operands/1/rewrites/0/scope").asText());
+ assertEquals(node.at("/query/operands/1/@type").asText(), "koral:token");
+ assertEquals(node.at("/query/operands/1/rewrites/0/scope").asText(), "@type(koral:queryRef)");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
index 85691ab..6642514 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/ResultRewriteTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.config.TestVariables;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -20,15 +19,11 @@
@Autowired
public RewriteHandler ha;
-
+
@Test
- public void testPostRewriteNothingToDo () throws KustvaktException {
- assertEquals("Handler could not be added to rewrite handler instance!",
- true, ha.add(CollectionRewrite.class));
-
+ public void testPostRewriteNothingToDo() throws KustvaktException {
+ assertEquals(true, ha.add(CollectionRewrite.class), "Handler could not be added to rewrite handler instance!");
String v = ha.processResult(TestVariables.RESULT, null);
- assertEquals("results do not match",
- JsonUtils.readTree(TestVariables.RESULT), JsonUtils.readTree(v));
+ assertEquals(JsonUtils.readTree(TestVariables.RESULT), JsonUtils.readTree(v), "results do not match");
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
index 135e209..60b934c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/RewriteHandlerTest.java
@@ -1,103 +1,155 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.query.serialize.QuerySerializer;
-/** EM: to do: Fix tests
- * New DB does not save users.
- *
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
+/**
+ * EM: to do: Fix tests
+ * New DB does not save users.
+ *
* @author hanl
* @date 21/10/2015
*/
+// @Deprecated
+// @Test
+// public void testRewriteNoBeanInject () throws KustvaktException {
+// RewriteHandler handler = new RewriteHandler(config);
+// QuerySerializer s = new QuerySerializer();
+// s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
+// assertTrue(handler.add(FoundryInject.class));
+// String res = handler.processQuery(s.toJSON(), null);
+// assertNotNull(res);
+// }
+//
+// @Deprecated
+// @Test
+// public void testRewriteBeanInject () throws KustvaktException {
+// RewriteHandler handler = new RewriteHandler(config);
+// QuerySerializer s = new QuerySerializer();
+// s.setQuery("[base=laufen | tt/pos=VVFIN]", "poliqarp");
+// assertTrue(handler.add(FoundryInject.class));
+// String res = handler.processQuery(s.toJSON(), null);
+// JsonNode node = JsonUtils.readTree(res);
+// assertNotNull(node);
+// assertEquals("tt", node.at("/query/wrap/operands/0/foundry")
+// .asText());
+// assertEquals("tt", node.at("/query/wrap/operands/1/foundry")
+// .asText());
+// }
+// EM: Fix me usersetting
+// @Test
+// @Ignore
+// public void testRewriteUserSpecific () throws KustvaktException {
+// RewriteHandler handler = new RewriteHandler(config);
+// QuerySerializer s = new QuerySerializer();
+// s.setQuery("[base=laufen|tt/pos=VFIN]", "poliqarp");
+// assertTrue(handler.add(FoundryInject.class));
+// String res = handler.processQuery(s.toJSON(), helper().getUser());
+// JsonNode node = JsonUtils.readTree(res);
+// assertNotNull(node);
+// assertEquals("tt_test",
+// node.at("/query/wrap/operands/0/foundry").asText());
+// assertNotEquals("tt_test",
+// node.at("/query/wrap/operands/1/foundry").asText());
+// }
+// EM: Fix me usersetting
+// @Override
+// public void initMethod () throws KustvaktException {
+// helper().setupAccount();
+// UserDataDbIface settingsdao = BeansFactory.getTypeFactory()
+// .getTypeInterfaceBean(
+// helper().getContext().getUserDataProviders(),
+// UserSettings.class);
+// assertNotNull(settingsdao);
+// UserSettings s = (UserSettings) settingsdao.get(helper().getUser());
+// s.setField(Attributes.DEFAULT_LEMMA_FOUNDRY, "tt_test");
+// settingsdao.update(s);
+// }
public class RewriteHandlerTest extends SpringJerseyTest {
@Autowired
private KustvaktConfiguration config;
-
+
@Test
- public void testRewriteTaskAdd () {
+ public void testRewriteTaskAdd() {
RewriteHandler handler = new RewriteHandler(config);
assertTrue(handler.add(FoundryInject.class));
assertTrue(handler.add(CollectionCleanRewrite.class));
assertTrue(handler.add(IdWriter.class));
}
-
// throws exception cause of missing configuration
- @Test(expected = RuntimeException.class)
- public void testRewriteConfigThrowsException () throws KustvaktException {
- RewriteHandler handler = new RewriteHandler();
- QuerySerializer s = new QuerySerializer();
- s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
- assertTrue(handler.add(FoundryInject.class));
- handler.processQuery(s.toJSON(), null);
+ @Test
+ public void testRewriteConfigThrowsException() {
+ assertThrows(RuntimeException.class, () -> {
+ RewriteHandler handler = new RewriteHandler();
+ QuerySerializer s = new QuerySerializer();
+ s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
+ assertTrue(handler.add(FoundryInject.class));
+ handler.processQuery(s.toJSON(), null);
+ });
}
-
-// @Deprecated
-// @Test
-// public void testRewriteNoBeanInject () throws KustvaktException {
-// RewriteHandler handler = new RewriteHandler(config);
-// QuerySerializer s = new QuerySerializer();
-// s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
-// assertTrue(handler.add(FoundryInject.class));
-// String res = handler.processQuery(s.toJSON(), null);
-// assertNotNull(res);
-// }
-//
-// @Deprecated
-// @Test
-// public void testRewriteBeanInject () throws KustvaktException {
-// RewriteHandler handler = new RewriteHandler(config);
-// QuerySerializer s = new QuerySerializer();
-// s.setQuery("[base=laufen | tt/pos=VVFIN]", "poliqarp");
-// assertTrue(handler.add(FoundryInject.class));
-// String res = handler.processQuery(s.toJSON(), null);
-// JsonNode node = JsonUtils.readTree(res);
-// assertNotNull(node);
-// assertEquals("tt", node.at("/query/wrap/operands/0/foundry")
-// .asText());
-// assertEquals("tt", node.at("/query/wrap/operands/1/foundry")
-// .asText());
-// }
-
+ // @Deprecated
+ // @Test
+ // public void testRewriteNoBeanInject () throws KustvaktException {
+ // RewriteHandler handler = new RewriteHandler(config);
+ // QuerySerializer s = new QuerySerializer();
+ // s.setQuery("[(base=laufen | base=gehen) & tt/pos=VVFIN]", "poliqarp");
+ // assertTrue(handler.add(FoundryInject.class));
+ // String res = handler.processQuery(s.toJSON(), null);
+ // assertNotNull(res);
+ // }
+ //
+ // @Deprecated
+ // @Test
+ // public void testRewriteBeanInject () throws KustvaktException {
+ // RewriteHandler handler = new RewriteHandler(config);
+ // QuerySerializer s = new QuerySerializer();
+ // s.setQuery("[base=laufen | tt/pos=VVFIN]", "poliqarp");
+ // assertTrue(handler.add(FoundryInject.class));
+ // String res = handler.processQuery(s.toJSON(), null);
+ // JsonNode node = JsonUtils.readTree(res);
+ // assertNotNull(node);
+ // assertEquals("tt", node.at("/query/wrap/operands/0/foundry")
+ // .asText());
+ // assertEquals("tt", node.at("/query/wrap/operands/1/foundry")
+ // .asText());
+ // }
// EM: Fix me usersetting
-// @Test
-// @Ignore
-// public void testRewriteUserSpecific () throws KustvaktException {
-// RewriteHandler handler = new RewriteHandler(config);
-// QuerySerializer s = new QuerySerializer();
-// s.setQuery("[base=laufen|tt/pos=VFIN]", "poliqarp");
-// assertTrue(handler.add(FoundryInject.class));
-// String res = handler.processQuery(s.toJSON(), helper().getUser());
-// JsonNode node = JsonUtils.readTree(res);
-// assertNotNull(node);
-// assertEquals("tt_test",
-// node.at("/query/wrap/operands/0/foundry").asText());
-// assertNotEquals("tt_test",
-// node.at("/query/wrap/operands/1/foundry").asText());
-// }
-
- // EM: Fix me usersetting
-// @Override
-// public void initMethod () throws KustvaktException {
-// helper().setupAccount();
-// UserDataDbIface settingsdao = BeansFactory.getTypeFactory()
-// .getTypeInterfaceBean(
-// helper().getContext().getUserDataProviders(),
-// UserSettings.class);
-// assertNotNull(settingsdao);
-// UserSettings s = (UserSettings) settingsdao.get(helper().getUser());
-// s.setField(Attributes.DEFAULT_LEMMA_FOUNDRY, "tt_test");
-// settingsdao.update(s);
-// }
-
-
-
+ // @Test
+ // @Ignore
+ // public void testRewriteUserSpecific () throws KustvaktException {
+ // RewriteHandler handler = new RewriteHandler(config);
+ // QuerySerializer s = new QuerySerializer();
+ // s.setQuery("[base=laufen|tt/pos=VFIN]", "poliqarp");
+ // assertTrue(handler.add(FoundryInject.class));
+ // String res = handler.processQuery(s.toJSON(), helper().getUser());
+ // JsonNode node = JsonUtils.readTree(res);
+ // assertNotNull(node);
+ // assertEquals("tt_test",
+ // node.at("/query/wrap/operands/0/foundry").asText());
+ // assertNotEquals("tt_test",
+ // node.at("/query/wrap/operands/1/foundry").asText());
+ // }
+ // EM: Fix me usersetting
+ // @Override
+ // public void initMethod () throws KustvaktException {
+ // helper().setupAccount();
+ // UserDataDbIface settingsdao = BeansFactory.getTypeFactory()
+ // .getTypeInterfaceBean(
+ // helper().getContext().getUserDataProviders(),
+ // UserSettings.class);
+ // assertNotNull(settingsdao);
+ // UserSettings s = (UserSettings) settingsdao.get(helper().getUser());
+ // s.setField(Attributes.DEFAULT_LEMMA_FOUNDRY, "tt_test");
+ // settingsdao.update(s);
+ // }
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java b/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
index 84a5056..135b516 100644
--- a/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/rewrite/VirtualCorpusRewriteTest.java
@@ -1,17 +1,17 @@
package de.ids_mannheim.korap.rewrite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
@@ -27,36 +27,26 @@
/**
* @author margaretha
- *
*/
public class VirtualCorpusRewriteTest extends SpringJerseyTest {
@Autowired
private NamedVCLoader vcLoader;
+
@Autowired
private QueryDao dao;
@Test
- public void testRefCachedVC ()
- throws KustvaktException, IOException, QueryException {
+ public void testRefCachedVC() throws KustvaktException, IOException, QueryException {
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains("named-vc1"));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo named-vc1")
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo named-vc1").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
-
- assertEquals("koral:docGroup", node.at("/@type").asText());
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
assertTrue(node.at("/operands/1/rewrites").isMissingNode());
-
testRefCachedVCWithUsername();
-
QueryDO vc = dao.retrieveQueryByName("named-vc1", "system");
dao.deleteQuery(vc);
vc = dao.retrieveQueryByName("named-vc1", "system");
@@ -65,94 +55,58 @@
assertFalse(VirtualCorpusCache.contains("named-vc1"));
}
- private void testRefCachedVCWithUsername ()
- throws KustvaktException, IOException, QueryException {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"system/named-vc1\"")
- .request()
- .get();
-
+ private void testRefCachedVCWithUsername() throws KustvaktException, IOException, QueryException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/named-vc1\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
- assertEquals("koral:docGroup", node.at("/@type").asText());
-
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
node = node.at("/operands/1/rewrites");
assertEquals(2, node.size());
- assertEquals("operation:deletion", node.at("/0/operation").asText());
- assertEquals("operation:insertion", node.at("/1/operation").asText());
-
+ assertEquals(node.at("/0/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/1/operation").asText(), "operation:insertion");
}
@Test
- public void testRewriteFreeAndSystemVCRef ()
- throws KustvaktException, Exception {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"system-vc\"")
- .request()
- .get();
-
+ public void testRewriteFreeAndSystemVCRef() throws KustvaktException, Exception {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system-vc\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
-
- assertEquals("koral:docGroup", node.at("/@type").asText());
- assertEquals("koral:doc", node.at("/operands/0/@type").asText());
-
- assertEquals("koral:doc", node.at("/operands/1/@type").asText());
- assertEquals("GOE", node.at("/operands/1/value").asText());
- assertEquals("corpusSigle", node.at("/operands/1/key").asText());
-
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/operands/1/value").asText(), "GOE");
+ assertEquals(node.at("/operands/1/key").asText(), "corpusSigle");
node = node.at("/operands/1/rewrites");
assertEquals(3, node.size());
- assertEquals("operation:deletion", node.at("/0/operation").asText());
- assertEquals("operation:deletion", node.at("/1/operation").asText());
- assertEquals("operation:insertion", node.at("/2/operation").asText());
+ assertEquals(node.at("/0/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/1/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/2/operation").asText(), "operation:insertion");
}
@Test
- public void testRewritePubAndSystemVCRef () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"system/system-vc\"")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("user", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ public void testRewritePubAndSystemVCRef() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/system-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("user", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
- assertEquals("koral:docGroup", node.at("/@type").asText());
- assertEquals("koral:docGroup", node.at("/operands/0/@type").asText());
-
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/operands/0/@type").asText(), "koral:docGroup");
node = node.at("/operands/1/rewrites");
assertEquals(3, node.size());
- assertEquals("operation:deletion", node.at("/0/operation").asText());
- assertEquals("operation:deletion", node.at("/1/operation").asText());
- assertEquals("operation:insertion", node.at("/2/operation").asText());
+ assertEquals(node.at("/0/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/1/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/2/operation").asText(), "operation:insertion");
}
@Test
- public void testRewriteWithDoryVCRef ()
- throws KustvaktException, IOException, QueryException {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Fisch").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"dory/dory-vc\"")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .get();
-
+ public void testRewriteWithDoryVCRef() throws KustvaktException, IOException, QueryException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Fisch").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
node = node.at("/collection");
- assertEquals("koral:docGroup", node.at("/@type").asText());
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
node = node.at("/operands/1/rewrites");
assertEquals(3, node.size());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java b/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
index 24f78ba..f83c127 100644
--- a/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/scenario/ICCTest.java
@@ -1,17 +1,15 @@
package de.ids_mannheim.korap.scenario;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.test.context.ContextConfiguration;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -22,16 +20,14 @@
/**
* <p>Test scenario for ICC (International Comparable Corpus)
* instance</p>
- *
- *
+ * <p>
* The instance requires user authentication and access to data is
* restricted to only logged-in users.
- *
- *
+ * <p>
* This class uses <em>test-config-icc.xml</em> spring XML config
* defining the location of a specific kustvakt configuration file for
- * this instance:<em>kustvakt-icc.conf</em>.
- *
+ * this instance:<em>kustvakt-icc.conf</em>.
+ *
* <p>
* To run a Kustvakt jar with ICC setup, the following files are needed:
* </p>
@@ -40,90 +36,90 @@
* <li>a Kustvakt configuration file that must be placed at the jar folder</li>
* <li>a JDBC properties file that must be placed at the jar folder</li>
* </ul>
- *
+ * <p>
* Example:
- *
+ *
* <p>
* <code>
* java -jar Kustvakt-full-0.69.3.jar --spring-config
* test-config-icc.xml
* </code>
* </p>
- *
+ *
* <h1>Spring configuration file</h1>
* <p>
* For ICC, collectionRewrite in the Spring XML configuration must
* be disabled. This has been done in <em>test-config-icc.xml</em>.
* </p>
- *
+ *
* <p>For testing, the ICC configuration uses HTTP Basic
* Authentication and doesn't use LDAP.</p>
- *
+ *
* <p>For production, Basic Authentication must be
* disabled/commented.</p>
- *
+ *
* <pre><code>
* <bean id="basic_auth"
* class="de.ids_mannheim.korap.authentication.BasicAuthentication"/>
- *
+ *
* <util:list id="kustvakt_authproviders"
* value-type="de.ids_mannheim.korap.interfaces.AuthenticationIface">
* <!-- <ref bean="basic_auth" /> -->
* </code>
* </pre>
- *
+ *
* <p>For production, the init-method of Initializator should be changed to init.</p>
- *
+ *
* <pre>
* <code>
* <bean id="initializator" class="de.ids_mannheim.de.init.Initializator"
- init-method="init"></bean>
+ * init-method="init"></bean>
* </code>
* </pre>
- *
+ *
* <h1>Kustvakt configuration file</h1>
- *
+ *
* <p>
* The configuration file: <em>kustvakt-icc.conf</em> includes the
* following setup:
* </p>
- *
+ *
* <ul>
* <li>
* <em>krill.indexDir</em> should indicate the location of the index.
* It is set to the wiki-index for the test.
* </li>
- *
+ *
* <p>
* <code>krill.indexDir=../wiki-index</code>
* </p>
- *
+ *
* <li>
* <em>availability.regex</em>
* properties should be removed or commented since the data doesn't
* contain availability and access to data is not determined by this
* field.
* </li>
- *
+ *
* <li>
* Resource filter class names for the search and match info services
* should be defined by <em>search.resource.filters property</em>. For
* example, to restricts access with only authentication filter:</li>
- *
+ *
* <p>
* <code>search.resource.filters=AuthenticationFilter </code>
* </p>
- *
+ *
* <li><em>oauth2.password.authentication</em> indicating the
* authentication method to match usernames and password.
* <code>TEST</code> is a dummy authentication that doesn't do any
* matching. For production, it must be changed to
* <code>LDAP</code>.</li>
- *
+ *
* <p><code>oauth2.password.authentication=LDAP</code></p>
- *
+ *
* </ul>
- *
+ *
* @author elma
* @see /src/main/resources/properties/jdbc.properties
*/
@@ -131,68 +127,46 @@
public class ICCTest extends SpringJerseyTest {
public final static String API_VERSION = "v1.0";
+
public String basicAuth;
- public ICCTest () throws KustvaktException {
- basicAuth = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("user", "password");
+ public ICCTest() throws KustvaktException {
+ basicAuth = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("user", "password");
}
@Test
- public void searchWithoutLogin () throws KustvaktException {
- Response r = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .request().get();
-
+ public void searchWithoutLogin() throws KustvaktException {
+ Response r = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), r.getStatus());
-
String entity = r.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void searchWithLogin () throws KustvaktException {
- Response r = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .request().header(Attributes.AUTHORIZATION, basicAuth).get();
-
+ public void searchWithLogin() throws KustvaktException {
+ Response r = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, basicAuth).get();
assertEquals(Status.OK.getStatusCode(), r.getStatus());
-
String entity = r.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/matches").size() > 0);
}
@Test
- public void matchInfoWithoutLogin () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("WDD17").path("982").path("72848").path("p2815-2816")
- .queryParam("foundry", "*").request().get();
-
+ public void matchInfoWithoutLogin() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("WDD17").path("982").path("72848").path("p2815-2816").queryParam("foundry", "*").request().get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void matchInfoWithLogin () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("WDD17").path("982").path("72848").path("p2815-2816")
- .queryParam("foundry", "*").request()
- .header(Attributes.AUTHORIZATION, basicAuth).get();
-
+ public void matchInfoWithLogin() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("WDD17").path("982").path("72848").path("p2815-2816").queryParam("foundry", "*").request().header(Attributes.AUTHORIZATION, basicAuth).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertTrue(node.at("/hasSnippet").asBoolean());
assertNotNull(node.at("/matchID").asText());
assertNotNull(node.at("/snippet").asText());
diff --git a/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java b/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
index b669ade..79f640f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/server/EmbeddedLdapServerTest.java
@@ -3,8 +3,8 @@
import com.unboundid.ldap.sdk.LDAPException;
import com.unboundid.util.Base64;
import de.ids_mannheim.korap.authentication.LdapAuth3;
-import org.junit.AfterClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Test;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
@@ -16,14 +16,15 @@
import static de.ids_mannheim.korap.authentication.LdapAuth3.LDAP_AUTH_ROK;
import static de.ids_mannheim.korap.authentication.LdapAuth3.LDAP_AUTH_RUNKNOWN;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
public class EmbeddedLdapServerTest {
public static final String TEST_EMBEDDED_LDAP_CONF = "src/test/resources/test-embedded-ldap.conf";
- @AfterClass
- public static void shutdownEmbeddedLdapServer() {
+ @AfterAll
+ static void shutdownEmbeddedLdapServer() {
EmbeddedLdapServer.stop();
}
@@ -58,14 +59,13 @@
KeySpec spec = new PBEKeySpec("password5".toCharArray(), salt, 65536, 256);
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2withHmacSHA256");
byte[] hash = f.generateSecret(spec).getEncoded();
-
final String pbkdf2sha256Password = "{PBKDF2-SHA256}" + Base64.encode(hash);
-// System.out.println(pbkdf2sha256Password);
+ // System.out.println(pbkdf2sha256Password);
assertEquals(LDAP_AUTH_ROK, LdapAuth3.login("user5", pbkdf2sha256Password, TEST_EMBEDDED_LDAP_CONF));
}
@Test
- public void loginWithUnEncodedPBKDF2PasswordFails() throws LDAPException, NoSuchAlgorithmException, InvalidKeySpecException {
+ public void loginWithUnencodedPBKDF2PasswordFails() throws LDAPException, NoSuchAlgorithmException, InvalidKeySpecException {
assertEquals(LDAP_AUTH_RUNKNOWN, LdapAuth3.login("user5", "password5", TEST_EMBEDDED_LDAP_CONF));
}
@@ -77,13 +77,12 @@
@Test
public void gettingMailForUser() throws LDAPException, UnknownHostException, GeneralSecurityException {
EmbeddedLdapServer.startIfNotRunning(TEST_EMBEDDED_LDAP_CONF);
- assertEquals("user2@example.com", LdapAuth3.getEmail("user2", TEST_EMBEDDED_LDAP_CONF));
+ assertEquals(LdapAuth3.getEmail("user2", TEST_EMBEDDED_LDAP_CONF), "user2@example.com");
}
@Test
- public void gettingMailFoRNAUTHUserIsNull() throws LDAPException, UnknownHostException, GeneralSecurityException {
+ public void gettingMailForNAUTHUserIsNull() throws LDAPException, UnknownHostException, GeneralSecurityException {
EmbeddedLdapServer.startIfNotRunning(TEST_EMBEDDED_LDAP_CONF);
assertEquals(null, LdapAuth3.getEmail("user1000", TEST_EMBEDDED_LDAP_CONF));
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
index 5faeb80..60a661f 100644
--- a/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/service/VirtualCorpusServiceTest.java
@@ -1,17 +1,16 @@
package de.ids_mannheim.korap.service;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.List;
-import org.junit.Assert;
-import org.junit.Test;
-import org.junit.runner.RunWith;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.springframework.test.context.junit.jupiter.SpringExtension;
import de.ids_mannheim.korap.constant.QueryType;
import de.ids_mannheim.korap.constant.ResourceType;
@@ -23,126 +22,95 @@
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.web.input.QueryJson;
-@RunWith(SpringJUnit4ClassRunner.class)
+@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:test-config.xml")
public class VirtualCorpusServiceTest {
@Autowired
private QueryService vcService;
+
@Autowired
private UserGroupService groupService;
@Test
- public void testCreateNonUniqueVC () throws KustvaktException {
-
+ public void testCreateNonUniqueVC() throws KustvaktException {
// EM: message differs depending on the database used
// for testing. The message below is from sqlite.
// thrown.expectMessage("A UNIQUE constraint failed "
// + "(UNIQUE constraint failed: virtual_corpus.name, "
// + "virtual_corpus.created_by)");
-
QueryJson vc = new QueryJson();
vc.setCorpusQuery("corpusSigle=GOE");
vc.setType(ResourceType.PRIVATE);
vc.setQueryType(QueryType.VIRTUAL_CORPUS);
-
- Assert.assertThrows(KustvaktException.class,
- () -> vcService.storeQuery(vc, "dory-vc", "dory", "dory"));
+ assertThrows(KustvaktException.class, () -> vcService.storeQuery(vc, "dory-vc", "dory", "dory"));
}
@Test
- public void createDeletePublishVC () throws KustvaktException {
+ public void createDeletePublishVC() throws KustvaktException {
String vcName = "new-published-vc";
-
QueryJson vc = new QueryJson();
vc.setCorpusQuery("corpusSigle=GOE");
vc.setType(ResourceType.PUBLISHED);
vc.setQueryType(QueryType.VIRTUAL_CORPUS);
String username = "VirtualCorpusServiceTest";
vcService.storeQuery(vc, vcName, username, username);
-
- List<QueryAccessDto> accesses =
- vcService.listQueryAccessByUsername("admin");
+ List<QueryAccessDto> accesses = vcService.listQueryAccessByUsername("admin");
int size = accesses.size();
-
QueryAccessDto dto = accesses.get(accesses.size() - 1);
assertEquals(vcName, dto.getQueryName());
- assertEquals("system", dto.getCreatedBy());
+ assertEquals(dto.getCreatedBy(), "system");
assertTrue(dto.getUserGroupName().startsWith("auto"));
-
// check hidden group
int groupId = dto.getUserGroupId();
UserGroup group = groupService.retrieveUserGroupById(groupId);
assertEquals(UserGroupStatus.HIDDEN, group.getStatus());
-
- //delete vc
- vcService.deleteQueryByName(username, vcName, username,
- QueryType.VIRTUAL_CORPUS);
-
+ // delete vc
+ vcService.deleteQueryByName(username, vcName, username, QueryType.VIRTUAL_CORPUS);
// check hidden access
accesses = vcService.listQueryAccessByUsername("admin");
- assertEquals(size-1, accesses.size());
-
+ assertEquals(size - 1, accesses.size());
// check hidden group
- KustvaktException e = assertThrows(KustvaktException.class,
- () -> groupService.retrieveUserGroupById(groupId));
- assertEquals("Group with id " + groupId + " is not found",
- e.getMessage());
+ KustvaktException e = assertThrows(KustvaktException.class, () -> groupService.retrieveUserGroupById(groupId));
+ assertEquals("Group with id " + groupId + " is not found", e.getMessage());
}
@Test
- public void testEditPublishVC () throws KustvaktException {
+ public void testEditPublishVC() throws KustvaktException {
String username = "dory";
int vcId = 2;
-
String vcName = "group-vc";
- QueryDO existingVC =
- vcService.searchQueryByName(username, vcName, username, QueryType.VIRTUAL_CORPUS);
+ QueryDO existingVC = vcService.searchQueryByName(username, vcName, username, QueryType.VIRTUAL_CORPUS);
QueryJson vcJson = new QueryJson();
vcJson.setType(ResourceType.PUBLISHED);
-
vcService.editQuery(existingVC, vcJson, vcName, username);
-
// check VC
QueryDto vcDto = vcService.searchQueryById("dory", vcId);
assertEquals(vcName, vcDto.getName());
- assertEquals(ResourceType.PUBLISHED.displayName(),
- vcDto.getType());
-
+ assertEquals(ResourceType.PUBLISHED.displayName(), vcDto.getType());
// check access
- List<QueryAccessDto> accesses =
- vcService.listQueryAccessByUsername("admin");
+ List<QueryAccessDto> accesses = vcService.listQueryAccessByUsername("admin");
int size = accesses.size();
QueryAccessDto dto = accesses.get(accesses.size() - 1);
assertEquals(vcName, dto.getQueryName());
- assertEquals("system", dto.getCreatedBy());
+ assertEquals(dto.getCreatedBy(), "system");
assertTrue(dto.getUserGroupName().startsWith("auto"));
-
// check auto hidden group
int groupId = dto.getUserGroupId();
UserGroup group = groupService.retrieveUserGroupById(groupId);
assertEquals(UserGroupStatus.HIDDEN, group.getStatus());
-
// 2nd edit (withdraw from publication)
-
vcJson = new QueryJson();
vcJson.setType(ResourceType.PROJECT);
-
vcService.editQuery(existingVC, vcJson, vcName, username);
-
// check VC
vcDto = vcService.searchQueryById("dory", vcId);
- assertEquals("group-vc", vcDto.getName());
+ assertEquals(vcDto.getName(), "group-vc");
assertEquals(ResourceType.PROJECT.displayName(), vcDto.getType());
-
// check access
accesses = vcService.listQueryAccessByUsername("admin");
assertEquals(size - 1, accesses.size());
-
- KustvaktException e = assertThrows(KustvaktException.class,
- () -> groupService.retrieveUserGroupById(groupId));
-
- assertEquals("Group with id " + groupId + " is not found", e.getMessage());
+ KustvaktException e = assertThrows(KustvaktException.class, () -> groupService.retrieveUserGroupById(groupId));
+ assertEquals("Group with id " + groupId + " is not found", e.getMessage());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java b/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
index f5d2fdd..513020e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/DataFactoryTest.java
@@ -1,72 +1,61 @@
package de.ids_mannheim.korap.user;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
-
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;
-/** Taken from UserdataTest
+/**
+ * Taken from UserdataTest
+ *
* @author hanl
* @date 27/01/2016
*/
public class DataFactoryTest {
@Test
- public void testDataFactoryAdd () throws KustvaktException {
+ public void testDataFactoryAdd() throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
-
data = "[]";
node = JsonUtils.readTree(data);
-
factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
}
-
@Test
- public void testDataFactoryGet () throws KustvaktException {
+ public void testDataFactoryGet() throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
Object value = factory.getValue(node, "field_1");
- assertEquals("value_1", value);
+ assertEquals(value, "value_1");
value = factory.getValue(node, "field_2");
assertEquals(20, value);
value = factory.getValue(node, "field_3");
assertEquals(true, value);
-
data = "[]";
node = JsonUtils.readTree(data);
-
assertTrue(factory.addValue(node, "", "value_2"));
assertTrue(factory.addValue(node, "", 10));
assertTrue(factory.addValue(node, "", false));
-
value = factory.getValue(node, "/0");
- assertEquals("value_2", value);
+ assertEquals(value, "value_2");
value = factory.getValue(node, "/1");
assertEquals(10, value);
value = factory.getValue(node, "/2");
@@ -74,38 +63,31 @@
}
@Test
- public void testDataFactoryMerge () throws KustvaktException {
+ public void testDataFactoryMerge() throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
-
data = "{}";
Object node2 = JsonUtils.readTree(data);
assertTrue(factory.addValue(node2, "field_1", "value_new"));
assertTrue(factory.addValue(node2, "field_2", "value_next"));
assertTrue(factory.addValue(node2, "field_4", "value_2"));
assertTrue(factory.addValue(node2, "field_7", "value_3"));
-
JsonNode node_new = (JsonNode) factory.merge(node, node2);
-
- assertEquals("value_new", node_new.path("field_1").asText());
- assertEquals("value_next", node_new.path("field_2").asText());
+ assertEquals(node_new.path("field_1").asText(), "value_new");
+ assertEquals(node_new.path("field_2").asText(), "value_next");
assertEquals(true, node_new.path("field_3").asBoolean());
- assertEquals("value_2", node_new.path("field_4").asText());
- assertEquals("value_3", node_new.path("field_7").asText());
-
+ assertEquals(node_new.path("field_4").asText(), "value_2");
+ assertEquals(node_new.path("field_7").asText(), "value_3");
}
-
+
@Test
- public void testDataFactoryKeys () throws KustvaktException {
+ public void testDataFactoryKeys() throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
@@ -115,72 +97,60 @@
}
@Test
- @Ignore
- public void testDataFactoryRemove () throws KustvaktException {
+ @Disabled
+ public void testDataFactoryRemove() throws KustvaktException {
String data = "{}";
Object node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
Object value = factory.getValue(node, "field_1");
- assertEquals("value_1", value);
+ assertEquals(value, "value_1");
value = factory.getValue(node, "field_2");
assertEquals(20, value);
value = factory.getValue(node, "field_3");
assertEquals(true, value);
-
assertTrue(factory.removeValue(node, "field_1"));
assertTrue(factory.removeValue(node, "field_2"));
assertTrue(factory.removeValue(node, "field_3"));
assertNotNull(node);
- assertEquals("{}", node.toString());
-
+ assertEquals(node.toString(), "{}");
data = "[]";
node = JsonUtils.readTree(data);
-
assertTrue(factory.addValue(node, "", "value_2"));
assertTrue(factory.addValue(node, "", 10));
assertTrue(factory.addValue(node, "", false));
-
value = factory.getValue(node, "/0");
- assertEquals("value_2", value);
+ assertEquals(value, "value_2");
value = factory.getValue(node, "/1");
assertEquals(10, value);
value = factory.getValue(node, "/2");
assertEquals(false, value);
-
-
// fixme: cannot be removed
assertTrue(factory.removeValue(node, "0"));
assertTrue(factory.removeValue(node, "1"));
assertTrue(factory.removeValue(node, "2"));
assertNotNull(node);
- assertEquals("[]", node.toString());
+ assertEquals(node.toString(), "[]");
}
-
+
@Test
- public void testDataFactoryEmbeddedProperty () throws KustvaktException {
+ public void testDataFactoryEmbeddedProperty() throws KustvaktException {
String data = "{}";
JsonNode node = JsonUtils.readTree(data);
-
DataFactory factory = DataFactory.getFactory();
assertTrue(factory.addValue(node, "field_1", "value_1"));
assertTrue(factory.addValue(node, "field_2", 20));
assertTrue(factory.addValue(node, "field_3", true));
-
ArrayNode array = JsonUtils.createArrayNode();
array.add(10);
array.add("v1");
array.add("v2");
factory.addValue(node, "field_3", array);
-
assertNotNull(node);
assertEquals(10, node.at("/field_3/0").asInt());
- assertEquals("v1", node.at("/field_3/1").asText());
- assertEquals("v2", node.at("/field_3/2").asText());
-
+ assertEquals(node.at("/field_3/1").asText(), "v1");
+ assertEquals(node.at("/field_3/2").asText(), "v2");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
index c828b05..75f3e6b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/user/UserdataTest.java
@@ -1,24 +1,24 @@
package de.ids_mannheim.korap.user;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.node.ArrayNode;
-
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;
import de.ids_mannheim.korap.validator.ApacheValidator;
import edu.emory.mathcs.backport.java.util.Arrays;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+
/**
* @author hanl, margaretha
* @date 27/01/2016
@@ -27,38 +27,36 @@
// EM: added
@Test
- public void testReadEmptyMap () throws KustvaktException {
+ public void testReadEmptyMap() throws KustvaktException {
Userdata userData = new UserSettingProcessor();
userData.read(new HashMap<>(), false);
String jsonSettings = userData.serialize();
- assertEquals("{}", jsonSettings);
+ assertEquals(jsonSettings, "{}");
}
@Test
- public void testReadNullMap () throws KustvaktException {
+ public void testReadNullMap() throws KustvaktException {
Userdata userData = new UserSettingProcessor();
userData.read(null, false);
String jsonSettings = userData.serialize();
- assertEquals("{}", jsonSettings);
+ assertEquals(jsonSettings, "{}");
}
// EM: based on MH code, supposedly to validate entries like email
// and date. See ApacheValidator
- //
+ //
// It has inconsistent behaviors:
// throws exceptions when there are invalid entries in a list,
// otherwise skips invalid entries and returns a valid map
// Moreover, Userdata.validate(ValidatorIface) does not return a
// valid map.
- //
+ //
// At the moment, validation is not needed for default settings.
@Test
- public void testValidateMap () throws IOException, KustvaktException {
-
+ public void testValidateMap() throws IOException, KustvaktException {
Map<String, Object> map = new HashMap<>();
- map.put("k1", Arrays.asList(new String[] { "a", "b", "c" }));
- map.put("k2", Arrays.asList(new Integer[] { 1, 2, 3 }));
-
+ map.put("k1", Arrays.asList(new String[]{"a", "b", "c"}));
+ map.put("k2", Arrays.asList(new Integer[]{1, 2, 3}));
Userdata data = new UserSettingProcessor();
data.read(map, false);
data.validate(new ApacheValidator());
@@ -66,10 +64,9 @@
// EM: below are tests from MH
@Test
- public void testDataValidation () {
+ public void testDataValidation() {
Userdata data = new UserDetails(1);
data.setField(Attributes.COUNTRY, "Germany");
-
String[] req = data.requiredFields();
String[] r = data.findMissingFields();
assertNotEquals(0, r.length);
@@ -77,21 +74,19 @@
assertFalse(data.isValid());
}
-
@Test
- public void testSettingsValidation () {
+ public void testSettingsValidation() {
Userdata data = new UserSettingProcessor();
data.setField(Attributes.FILE_FORMAT_FOR_EXPORT, "export");
-
String[] req = data.requiredFields();
String[] r = data.findMissingFields();
assertEquals(0, r.length);
assertEquals(req.length, r.length);
assertTrue(data.isValid());
}
-
+
@Test
- public void testUserdataRequiredFields () throws KustvaktException {
+ public void testUserdataRequiredFields() throws KustvaktException {
UserDetails details = new UserDetails(-1);
Map<String, Object> m = new HashMap<>();
m.put(Attributes.FIRSTNAME, "first");
@@ -99,14 +94,13 @@
m.put(Attributes.ADDRESS, "address");
m.put(Attributes.EMAIL, "email");
details.setData(JsonUtils.toJSON(m));
-
details.setData(JsonUtils.toJSON(m));
String[] missing = details.findMissingFields();
assertEquals(0, missing.length);
}
@Test
- public void testUserdataDefaultFields () throws KustvaktException {
+ public void testUserdataDefaultFields() throws KustvaktException {
UserSettingProcessor settings = new UserSettingProcessor();
Map<String, Object> m = new HashMap<>();
m.put(Attributes.DEFAULT_FOUNDRY_RELATION, "rel_1");
@@ -116,38 +110,34 @@
m.put(Attributes.PAGE_LENGTH, 10);
m.put(Attributes.QUERY_LANGUAGE, "poliqarp");
m.put(Attributes.METADATA_QUERY_EXPERT_MODUS, false);
-
settings.read(m, true);
-
assertNotEquals(m.size(), settings.size());
assertEquals(settings.defaultFields().length, settings.size());
- assertEquals("rel_1", settings.get(Attributes.DEFAULT_FOUNDRY_RELATION));
- assertEquals("pos_1", settings.get(Attributes.DEFAULT_FOUNDRY_POS));
- assertEquals("lemma_1", settings.get(Attributes.DEFAULT_FOUNDRY_LEMMA));
- assertEquals("const_1", settings.get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT));
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_RELATION), "rel_1");
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_POS), "pos_1");
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_LEMMA), "lemma_1");
+ assertEquals(settings.get(Attributes.DEFAULT_FOUNDRY_CONSTITUENT), "const_1");
assertEquals(10, settings.get(Attributes.PAGE_LENGTH));
-
- }
-
- @Test(expected = KustvaktException.class)
- public void testUserDataRequiredFieldsException ()
- throws KustvaktException {
- UserDetails details = new UserDetails(-1);
- Map<String, Object> m = new HashMap<>();
- m.put(Attributes.FIRSTNAME, "first");
- m.put(Attributes.LASTNAME, "last");
- m.put(Attributes.ADDRESS, "address");
-
- details.setData(JsonUtils.toJSON(m));
- String[] missing = details.findMissingFields();
-
- assertEquals(1, missing.length);
- assertEquals("email", missing[0]);
- details.checkRequired();
}
@Test
- public void testUserDataPointerFunction () throws KustvaktException {
+ public void testUserDataRequiredFieldsException() {
+ assertThrows(KustvaktException.class, () -> {
+ UserDetails details = new UserDetails(-1);
+ Map<String, Object> m = new HashMap<>();
+ m.put(Attributes.FIRSTNAME, "first");
+ m.put(Attributes.LASTNAME, "last");
+ m.put(Attributes.ADDRESS, "address");
+ details.setData(JsonUtils.toJSON(m));
+ String[] missing = details.findMissingFields();
+ assertEquals(1, missing.length);
+ assertEquals(missing[0], "email");
+ details.checkRequired();
+ });
+ }
+
+ @Test
+ public void testUserDataPointerFunction() throws KustvaktException {
UserDetails details = new UserDetails(-1);
Map<String, Object> m = new HashMap<>();
m.put(Attributes.FIRSTNAME, "first");
@@ -155,29 +145,25 @@
m.put(Attributes.ADDRESS, "address");
m.put(Attributes.EMAIL, "email");
details.setData(JsonUtils.toJSON(m));
-
ArrayNode array = JsonUtils.createArrayNode();
array.add(100);
array.add("message");
details.setField("errors", array);
-
assertEquals(100, details.get("/errors/0"));
- assertEquals("message", details.get("/errors/1"));
+ assertEquals(details.get("/errors/1"), "message");
}
@Test
- public void testUserDataUpdate () {
+ public void testUserDataUpdate() {
UserDetails details = new UserDetails(-1);
details.setField(Attributes.FIRSTNAME, "first");
details.setField(Attributes.LASTNAME, "last");
details.setField(Attributes.ADDRESS, "address");
details.setField(Attributes.EMAIL, "email");
-
UserDetails details2 = new UserDetails(-1);
details2.setField(Attributes.COUNTRY, "Germany");
details.update(details2);
-
- assertEquals("first", details.get(Attributes.FIRSTNAME));
- assertEquals("Germany", details.get(Attributes.COUNTRY));
+ assertEquals(details.get(Attributes.FIRSTNAME), "first");
+ assertEquals(details.get(Attributes.COUNTRY), "Germany");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java b/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
index d83400a..4826743 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/ApiVersionTest.java
@@ -1,13 +1,12 @@
package de.ids_mannheim.korap.web;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
-
import javax.ws.rs.core.MediaType;
import org.eclipse.jetty.http.HttpStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import javax.ws.rs.core.Response;
@@ -16,31 +15,22 @@
/**
* @author margaretha
- *
*/
public class ApiVersionTest extends SpringJerseyTest {
@Test
- public void testSearchWithoutVersion () throws KustvaktException {
- Response response = target().path("api").path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .request()
- .accept(MediaType.APPLICATION_JSON).get();
+ public void testSearchWithoutVersion() throws KustvaktException {
+ Response response = target().path("api").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
- assertEquals("/api/"+API_VERSION+"/search", location.getPath());
+ assertEquals("/api/" + API_VERSION + "/search", location.getPath());
}
@Test
- public void testSearchWrongVersion () throws KustvaktException {
- Response response = target().path("api").path("v0.2")
- .path("search").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp")
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .get();
+ public void testSearchWrongVersion() throws KustvaktException {
+ Response response = target().path("api").path("v0.2").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
- assertEquals("/api/"+API_VERSION+"/search", location.getPath());
+ assertEquals("/api/" + API_VERSION + "/search", location.getPath());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
index c15da2d..2cdb620 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/InitialSuperClientTest.java
@@ -1,17 +1,16 @@
package de.ids_mannheim.korap.web;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.IOException;
-
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.FullConfiguration;
@@ -27,48 +26,38 @@
@Autowired
private FullConfiguration config;
+
@Autowired
private OAuth2ClientDao clientDao;
-
- private String path = KustvaktConfiguration.DATA_FOLDER + "/"
- + OAuth2InitClientService.TEST_OUTPUT_FILENAME;
+
+ private String path = KustvaktConfiguration.DATA_FOLDER + "/" + OAuth2InitClientService.TEST_OUTPUT_FILENAME;
@Test
- public void testCreatingInitialSuperClient ()
- throws IOException, KustvaktException {
+ public void testCreatingInitialSuperClient() throws IOException, KustvaktException {
assertTrue(config.createInitialSuperClient());
-
File f = new File(path);
assertTrue(f.exists());
-
JsonNode node = JsonUtils.readFile(path, JsonNode.class);
String superClientId = node.at("/client_id").asText();
String superClientSecret = node.at("/client_secret").asText();
-
OAuth2Client superClient = clientDao.retrieveClientById(superClientId);
assertTrue(superClient.isSuper());
-
testLogin(superClientId, superClientSecret);
-
removeSuperClientFile();
}
- private void testLogin (String superClientId, String superClientSecret)
- throws KustvaktException {
- Response response = requestTokenWithPassword(superClientId,
- superClientSecret, "username", "password");
-
+ private void testLogin(String superClientId, String superClientSecret) throws KustvaktException {
+ Response response = requestTokenWithPassword(superClientId, superClientSecret, "username", "password");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
assertTrue(!node.at("/access_token").isMissingNode());
assertTrue(!node.at("/refresh_token").isMissingNode());
assertTrue(!node.at("/expires_in").isMissingNode());
- assertEquals("all", node.at("/scope").asText());
- assertEquals("Bearer", node.at("/token_type").asText());
+ assertEquals(node.at("/scope").asText(), "all");
+ assertEquals(node.at("/token_type").asText(), "Bearer");
}
-
- private void removeSuperClientFile () {
+
+ private void removeSuperClientFile() {
File f = new File(path);
if (f.exists()) {
f.delete();
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
index 30d47d2..873f0a9 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/JettyServerTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.web;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.HttpURLConnection;
@@ -11,32 +11,29 @@
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ShutdownHandler;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
/**
* @author margaretha
- *
*/
public class JettyServerTest {
- @BeforeClass
- public static void testServerStarts () throws Exception {
+ @BeforeAll
+ static void testServerStarts() throws Exception {
Server server = new Server();
ServerConnector connector = new ServerConnector(server);
connector.setPort(8000);
- server.setConnectors(new Connector[] { connector });
-
+ server.setConnectors(new Connector[]{connector});
HandlerList handlers = new HandlerList();
handlers.addHandler(new ShutdownHandler("secret", false, true));
server.setHandler(handlers);
server.start();
}
-
+
@Test
- public void testShutdown () throws IOException {
- URL url = new URL(
- "http://localhost:8000/shutdown?token=secret");
+ public void testShutdown() throws IOException {
+ URL url = new URL("http://localhost:8000/shutdown?token=secret");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
assertEquals(200, connection.getResponseCode());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java b/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
index ec5561b..31df174 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/SearchKrillTest.java
@@ -1,16 +1,14 @@
package de.ids_mannheim.korap.web;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import javax.annotation.PostConstruct;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.KrillIndex;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -21,70 +19,63 @@
/**
* Created by hanl on 02.06.16.
- *
+ * <p>
* Updated by margaretha
*/
public class SearchKrillTest extends SpringJerseyTest {
@Autowired
KustvaktConfiguration config;
-
+
SearchKrill krill = null;
-
+
@PostConstruct
- private void createKrill () {
+ private void createKrill() {
krill = new SearchKrill(config.getIndexDir());
assertNotNull(krill);
}
@Test
- public void testIndex () throws KustvaktException {
+ public void testIndex() throws KustvaktException {
KrillIndex index = krill.getIndex();
assertNotNull(index);
}
@Test
- public void testDocSize () {
+ public void testDocSize() {
assertNotEquals(0, krill.getIndex().numberOf("documents"));
}
@Test
- public void testMatchInfo () throws KustvaktException {
- String matchinfo = krill.getMatch("WPD/AAA.00002/p169-197",
- config.getFreeLicensePattern());
+ public void testMatchInfo() throws KustvaktException {
+ String matchinfo = krill.getMatch("WPD/AAA.00002/p169-197", config.getFreeLicensePattern());
JsonNode node = JsonUtils.readTree(matchinfo);
- assertEquals("Invalid match identifier",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Invalid match identifier");
}
@Test
- public void testSearch () throws KustvaktException {
+ public void testSearch() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
-
String result = krill.search(s.toJSON());
-
JsonNode node = JsonUtils.readTree(result);
assertNotNull(node);
assertNotEquals(0, node.at("/matches").size());
}
@Test
- public void testTimeOut () throws KustvaktException {
+ public void testTimeOut() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
-// s.setQuery("node ->malt/d[func=/.*/] node", "annis");
-
+ // s.setQuery("node ->malt/d[func=/.*/] node", "annis");
MetaQueryBuilder meta = new MetaQueryBuilder();
meta.addEntry("timeout", 1);
s.setMeta(meta);
-
String query = s.toJSON();
JsonNode node = JsonUtils.readTree(query);
assertEquals(1, node.at("/meta/timeout").asInt());
-
String result = krill.search(query);
node = JsonUtils.readTree(result);
- assertEquals(true,node.at("/meta/timeExceeded").asBoolean());
+ assertEquals(true, node.at("/meta/timeExceeded").asBoolean());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
index 709d6f1..62f6a56 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AdminLoadVCTest.java
@@ -1,8 +1,8 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
@@ -10,10 +10,8 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.cache.VirtualCorpusCache;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -21,21 +19,14 @@
public class AdminLoadVCTest extends SpringJerseyTest {
@Test
- public void testLoadCacheVC () throws KustvaktException, InterruptedException {
+ public void testLoadCacheVC() throws KustvaktException, InterruptedException {
assertFalse(VirtualCorpusCache.contains("named-vc1"));
Form f = new Form();
f.param("token", "secret");
-
- Response response = target().path(API_VERSION).path("admin").path("vc")
- .path("load-cache").request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("vc").path("load-cache").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
Thread.sleep(100);
assertTrue(VirtualCorpusCache.contains("named-vc1"));
-
VirtualCorpusCache.reset();
assertFalse(VirtualCorpusCache.contains("named-vc1"));
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
index e005476..7a61c36 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AnnotationControllerTest.java
@@ -1,16 +1,15 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
import java.util.Map.Entry;
-
import javax.ws.rs.client.Entity;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -18,85 +17,63 @@
import de.ids_mannheim.korap.utils.JsonUtils;
public class AnnotationControllerTest extends SpringJerseyTest {
- @Test
- public void testAnnotationLayers () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("annotation").path("layers")
- .request()
- .get();
+ @Test
+ public void testAnnotationLayers() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("annotation").path("layers").request().get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
-
assertEquals(31, n.size());
n = n.get(0);
assertEquals(1, n.get("id").asInt());
-// assertEquals("opennlp/p", n.get("code").asText());
-// assertEquals("p", n.get("layer").asText());
-// assertEquals("opennlp", n.get("foundry").asText());
-// assertNotNull(n.get("description"));
+ // assertEquals("opennlp/p", n.get("code").asText());
+ // assertEquals("p", n.get("layer").asText());
+ // assertEquals("opennlp", n.get("foundry").asText());
+ // assertNotNull(n.get("description"));
}
@Test
- public void testAnnotationFoundry () throws KustvaktException {
+ public void testAnnotationFoundry() throws KustvaktException {
String json = "{\"codes\":[\"opennlp/*\"], \"language\":\"en\"}";
- Response response =
- target().path(API_VERSION).path("annotation")
- .path("description")
- .request()
- .post(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("annotation").path("description").request().post(Entity.json(json));
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
-
n = n.get(0);
- assertEquals("opennlp", n.get("code").asText());
- assertEquals("OpenNLP", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "opennlp");
+ assertEquals(n.get("description").asText(), "OpenNLP");
assertEquals(1, n.get("layers").size());
-
n = n.get("layers").get(0);
- assertEquals("p", n.get("code").asText());
- assertEquals("Part-of-Speech", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "p");
+ assertEquals(n.get("description").asText(), "Part-of-Speech");
assertEquals(52, n.get("keys").size());
-
n = n.get("keys").get(0);
- assertEquals("ADJA", n.get("code").asText());
- assertEquals("Attributive Adjective", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "ADJA");
+ assertEquals(n.get("description").asText(), "Attributive Adjective");
assertTrue(n.get("values") == null);
}
@Test
- public void testAnnotationValues () throws KustvaktException {
+ public void testAnnotationValues() throws KustvaktException {
String json = "{\"codes\":[\"mate/m\"], \"language\":\"en\"}";
- Response response =
- target().path(API_VERSION).path("annotation")
- .path("description")
- .request()
- .post(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("annotation").path("description").request().post(Entity.json(json));
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity);
-
n = n.get(0);
- assertEquals("mate", n.get("code").asText());
- assertEquals("Mate", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "mate");
+ assertEquals(n.get("description").asText(), "Mate");
assertEquals(1, n.get("layers").size());
-
n = n.get("layers").get(0);
- assertEquals("m", n.get("code").asText());
- assertEquals("Morphology", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "m");
+ assertEquals(n.get("description").asText(), "Morphology");
assertEquals(8, n.get("keys").size());
-
n = n.get("keys").get(1);
- assertEquals("case", n.get("code").asText());
- assertEquals("Case", n.get("description").asText());
+ assertEquals(n.get("code").asText(), "case");
+ assertEquals(n.get("description").asText(), "Case");
assertEquals(5, n.get("values").size());
-
n = n.get("values");
Iterator<Entry<String, JsonNode>> fields = n.fields();
Entry<String, JsonNode> e = fields.next();
- assertEquals("*", e.getKey());
- assertEquals("Undefined", e.getValue().asText());
+ assertEquals(e.getKey(), "*");
+ assertEquals(e.getValue().asText(), "Undefined");
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
index e2605ab..fa58f95 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/AvailabilityTest.java
@@ -1,13 +1,13 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -20,444 +20,264 @@
public class AvailabilityTest extends SpringJerseyTest {
- private void checkAndFree (String json) throws KustvaktException {
+ private void checkAndFree(String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
- assertEquals("availability",
- node.at("/collection/operands/0/key").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
}
-
- private void checkAndPublic (String json) throws KustvaktException {
+ private void checkAndPublic(String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
-
- assertEquals("operation:and",
- node.at("/collection/operation").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/0/operands/0/match").asText());
- assertEquals("type:regex",
- node.at("/collection/operands/0/operands/0/type").asText());
- assertEquals("availability",
- node.at("/collection/operands/0/operands/0/key").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/operands/0/value").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/0/operands/1/operands/0/match")
- .asText());
- assertEquals("ACA.*",
- node.at("/collection/operands/0/operands/1/operands/0/value")
- .asText());
- assertEquals("match:eq",
- node.at("/collection/operands/0/operands/1/operands/1/match")
- .asText());
- assertEquals("QAO-NC",
- node.at("/collection/operands/0/operands/1/operands/1/value")
- .asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(PUB)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/0/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/0/operands/0/type").asText(), "type:regex");
+ assertEquals(node.at("/collection/operands/0/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/0/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/0/operands/1/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/0/operands/1/operands/0/value").asText(), "ACA.*");
+ assertEquals(node.at("/collection/operands/0/operands/1/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/0/operands/1/operands/1/value").asText(), "QAO-NC");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
}
- private void checkAndPublicWithACA (String json) throws KustvaktException {
+ private void checkAndPublicWithACA(String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
- assertEquals("operation:and",
- node.at("/collection/operation").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(PUB)",
- node.at("/collection/rewrites/0/scope").asText());
-
- assertEquals("match:eq",
- node.at("/collection/operands/1/match").asText());
- assertEquals("type:regex",
- node.at("/collection/operands/1/type").asText());
- assertEquals("availability",
- node.at("/collection/operands/1/key").asText());
- assertEquals("ACA.*", node.at("/collection/operands/1/value").asText());
-
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
+ assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/1/type").asText(), "type:regex");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
node = node.at("/collection/operands/0");
- assertEquals("match:eq", node.at("/operands/0/match").asText());
- assertEquals("type:regex", node.at("/operands/0/type").asText());
- assertEquals("availability", node.at("/operands/0/key").asText());
- assertEquals("CC-BY.*", node.at("/operands/0/value").asText());
-
- assertEquals("match:eq",
- node.at("/operands/1/operands/0/match").asText());
- assertEquals("type:regex",
- node.at("/operands/1/operands/0/type").asText());
- assertEquals("availability",
- node.at("/operands/1/operands/0/key").asText());
- assertEquals("ACA.*", node.at("/operands/1/operands/0/value").asText());
-
-
+ assertEquals(node.at("/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/0/type").asText(), "type:regex");
+ assertEquals(node.at("/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/operands/1/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/1/operands/0/type").asText(), "type:regex");
+ assertEquals(node.at("/operands/1/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/operands/1/operands/0/value").asText(), "ACA.*");
}
- private void checkAndAllWithACA (String json) throws KustvaktException {
+ private void checkAndAllWithACA(String json) throws KustvaktException {
JsonNode node = JsonUtils.readTree(json);
assertNotNull(node);
- assertEquals("operation:and",
- node.at("/collection/operation").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
-
- assertEquals("match:eq",
- node.at("/collection/operands/1/match").asText());
- assertEquals("type:regex",
- node.at("/collection/operands/1/type").asText());
- assertEquals("availability",
- node.at("/collection/operands/1/key").asText());
- assertEquals("ACA.*", node.at("/collection/operands/1/value").asText());
-
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/1/type").asText(), "type:regex");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
node = node.at("/collection/operands/0");
-
- assertEquals("match:eq", node.at("/operands/0/match").asText());
- assertEquals("type:regex", node.at("/operands/0/type").asText());
- assertEquals("availability", node.at("/operands/0/key").asText());
- assertEquals("CC-BY.*", node.at("/operands/0/value").asText());
- assertEquals("match:eq",
- node.at("/operands/1/operands/1/operands/0/match").asText());
- assertEquals("QAO-NC",
- node.at("/operands/1/operands/1/operands/0/value").asText());
- assertEquals("match:eq",
- node.at("/operands/1/operands/1/operands/1/match").asText());
- assertEquals("QAO.*",
- node.at("/operands/1/operands/1/operands/1/value").asText());
-
+ assertEquals(node.at("/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/0/type").asText(), "type:regex");
+ assertEquals(node.at("/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/operands/1/operands/1/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/1/operands/1/operands/0/value").asText(), "QAO-NC");
+ assertEquals(node.at("/operands/1/operands/1/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/1/operands/1/operands/1/value").asText(), "QAO.*");
}
-
-
- private Response searchQuery (String collectionQuery) {
- return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]")
- .queryParam("ql", "poliqarp").queryParam("cq", collectionQuery)
- .request()
- .get();
+ private Response searchQuery(String collectionQuery) {
+ return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", collectionQuery).request().get();
}
-
- private Response searchQueryWithIP (String collectionQuery, String ip)
- throws ProcessingException,
- KustvaktException {
- return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]")
- .queryParam("ql", "poliqarp").queryParam("cq", collectionQuery)
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, ip)
- .get();
+ private Response searchQueryWithIP(String collectionQuery, String ip) throws ProcessingException, KustvaktException {
+ return target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", collectionQuery).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, ip).get();
}
-
@Test
- public void testAvailabilityFreeAuthorized () throws KustvaktException {
+ public void testAvailabilityFreeAuthorized() throws KustvaktException {
Response response = searchQuery("availability = CC-BY-SA");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityRegexFreeAuthorized ()
- throws KustvaktException {
+ public void testAvailabilityRegexFreeAuthorized() throws KustvaktException {
Response response = searchQuery("availability = /.*BY.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityFreeUnauthorized () throws KustvaktException {
+ public void testAvailabilityFreeUnauthorized() throws KustvaktException {
Response response = searchQuery("availability = ACA-NC");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityRegexFreeUnauthorized ()
- throws KustvaktException {
+ public void testAvailabilityRegexFreeUnauthorized() throws KustvaktException {
Response response = searchQuery("availability = /ACA.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexNoRewrite () throws KustvaktException {
- Response response = searchQuery(
- "availability = /CC-BY.*/ & availability = /ACA.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityRegexNoRewrite() throws KustvaktException {
+ Response response = searchQuery("availability = /CC-BY.*/ & availability = /ACA.*/");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String json = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(json);
- assertEquals("operation:and",
- node.at("/collection/operation").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/0/match").asText());
- assertEquals("type:regex",
- node.at("/collection/operands/0/type").asText());
- assertEquals("availability",
- node.at("/collection/operands/0/key").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/1/match").asText());
- assertEquals("ACA.*", node.at("/collection/operands/1/value").asText());
-
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
+ assertEquals(node.at("/collection/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/0/type").asText(), "type:regex");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
}
-
@Test
- public void testAvailabilityRegexFreeUnauthorized3 ()
- throws KustvaktException {
+ public void testAvailabilityRegexFreeUnauthorized3() throws KustvaktException {
Response response = searchQuery("availability = /.*NC.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
// System.out.println(response.readEntity(String.class));
checkAndFree(response.readEntity(String.class));
}
-
-
@Test
- public void testNegationAvailabilityFreeUnauthorized ()
- throws KustvaktException {
+ public void testNegationAvailabilityFreeUnauthorized() throws KustvaktException {
Response response = searchQuery("availability != /CC-BY.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityFreeUnauthorized2 ()
- throws KustvaktException {
+ public void testNegationAvailabilityFreeUnauthorized2() throws KustvaktException {
Response response = searchQuery("availability != /.*BY.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testNegationAvailabilityWithOperationOrUnauthorized ()
- throws KustvaktException {
- Response response = searchQuery(
- "availability = /CC-BY.*/ | availability != /CC-BY.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testNegationAvailabilityWithOperationOrUnauthorized() throws KustvaktException {
+ Response response = searchQuery("availability = /CC-BY.*/ | availability != /CC-BY.*/");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testComplexNegationAvailabilityFreeUnauthorized ()
- throws KustvaktException {
- Response response =
- searchQuery("textClass=politik & availability != /CC-BY.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testComplexNegationAvailabilityFreeUnauthorized() throws KustvaktException {
+ Response response = searchQuery("textClass=politik & availability != /CC-BY.*/");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testComplexAvailabilityFreeUnauthorized ()
- throws KustvaktException {
- Response response =
- searchQuery("textClass=politik & availability=ACA-NC");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testComplexAvailabilityFreeUnauthorized() throws KustvaktException {
+ Response response = searchQuery("textClass=politik & availability=ACA-NC");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testComplexAvailabilityFreeUnauthorized3 ()
- throws KustvaktException {
- Response response =
- searchQuery("textClass=politik & availability=/.*NC.*/");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testComplexAvailabilityFreeUnauthorized3() throws KustvaktException {
+ Response response = searchQuery("textClass=politik & availability=/.*NC.*/");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityPublicAuthorized () throws KustvaktException {
- Response response =
- searchQueryWithIP("availability=ACA-NC", "149.27.0.32");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityPublicAuthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability=ACA-NC", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityPublicUnauthorized () throws KustvaktException {
- Response response =
- searchQueryWithIP("availability=QAO-NC-LOC:ids", "149.27.0.32");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityPublicUnauthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability=QAO-NC-LOC:ids", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
-
@Test
- public void testAvailabilityRegexPublicAuthorized ()
- throws KustvaktException {
- Response response =
- searchQueryWithIP("availability= /ACA.*/", "149.27.0.32");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityRegexPublicAuthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability= /ACA.*/", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublicWithACA(response.readEntity(String.class));
}
-
@Test
- public void testNegationAvailabilityPublicUnauthorized ()
- throws KustvaktException {
- Response response =
- searchQueryWithIP("availability != ACA-NC", "149.27.0.32");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
- checkAndPublic(response.readEntity(String.class));
- }
-
-
- @Test
- public void testNegationAvailabilityRegexPublicUnauthorized ()
- throws KustvaktException {
- Response response =
- searchQueryWithIP("availability != /ACA.*/", "149.27.0.32");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
- checkAndPublic(response.readEntity(String.class));
- }
-
-
- @Test
- public void testComplexAvailabilityPublicUnauthorized ()
- throws KustvaktException {
- Response response = searchQueryWithIP(
- "textClass=politik & availability=QAO-NC-LOC:ids",
- "149.27.0.32");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
- checkAndPublic(response.readEntity(String.class));
- }
-
-
- @Test
- public void testNegationComplexAvailabilityPublicUnauthorized ()
- throws KustvaktException {
- Response response = searchQueryWithIP(
- "textClass=politik & availability!=QAO-NC-LOC:ids",
- "149.27.0.32");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testNegationAvailabilityPublicUnauthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability != ACA-NC", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndPublic(response.readEntity(String.class));
}
@Test
- public void testAvailabilityRegexAllAuthorized () throws KustvaktException {
- Response response =
- searchQueryWithIP("availability= /ACA.*/", "10.27.0.32");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testNegationAvailabilityRegexPublicUnauthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability != /ACA.*/", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ checkAndPublic(response.readEntity(String.class));
+ }
+ @Test
+ public void testComplexAvailabilityPublicUnauthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("textClass=politik & availability=QAO-NC-LOC:ids", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ checkAndPublic(response.readEntity(String.class));
+ }
+
+ @Test
+ public void testNegationComplexAvailabilityPublicUnauthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("textClass=politik & availability!=QAO-NC-LOC:ids", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ checkAndPublic(response.readEntity(String.class));
+ }
+
+ @Test
+ public void testAvailabilityRegexAllAuthorized() throws KustvaktException {
+ Response response = searchQueryWithIP("availability= /ACA.*/", "10.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndAllWithACA(response.readEntity(String.class));
}
@Test
- public void testAvailabilityOr () throws KustvaktException {
- Response response =
- searchQuery("availability=/CC-BY.*/ | availability=/ACA.*/");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityOr() throws KustvaktException {
+ Response response = searchQuery("availability=/CC-BY.*/ | availability=/ACA.*/");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testRedundancyOrPub () throws KustvaktException {
- Response response = searchQueryWithIP(
- "availability=/CC-BY.*/ | availability=/ACA.*/ | availability=/QAO-NC/",
- "149.27.0.32");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testRedundancyOrPub() throws KustvaktException {
+ Response response = searchQueryWithIP("availability=/CC-BY.*/ | availability=/ACA.*/ | availability=/QAO-NC/", "149.27.0.32");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String json = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(json);
assertTrue(node.at("/collection/rewrites").isMissingNode());
- assertEquals("operation:or", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/operation").asText(), "operation:or");
}
@Test
- public void testAvailabilityOrCorpusSigle () throws KustvaktException {
- Response response =
- searchQuery("availability=/CC-BY.*/ | corpusSigle=GOE");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testAvailabilityOrCorpusSigle() throws KustvaktException {
+ Response response = searchQuery("availability=/CC-BY.*/ | corpusSigle=GOE");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testOrWithoutAvailability () throws KustvaktException {
- Response response =
- searchQuery("corpusSigle=GOE | textClass=politik");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testOrWithoutAvailability() throws KustvaktException {
+ Response response = searchQuery("corpusSigle=GOE | textClass=politik");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
@Test
- public void testWithoutAvailability () throws KustvaktException {
+ public void testWithoutAvailability() throws KustvaktException {
Response response = searchQuery("corpusSigle=GOE");
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
checkAndFree(response.readEntity(String.class));
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
index dbe693a..a6b4457 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/FreeResourceControllerTest.java
@@ -1,11 +1,11 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.test.context.ContextConfiguration;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -14,21 +14,16 @@
@ContextConfiguration("classpath:test-resource-config.xml")
public class FreeResourceControllerTest extends SpringJerseyTest {
-
- @Test
- public void testResource () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("resource")
- .request()
- .get();
+ @Test
+ public void testResource() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("resource").request().get();
String entity = response.readEntity(String.class);
JsonNode n = JsonUtils.readTree(entity).get(0);
- assertEquals("WPD17",n.at("/resourceId").asText());
- assertEquals("Deutsche Wikipedia Artikel 2017", n.at("/titles/de").asText());
- assertEquals("German Wikipedia Articles 2017", n.at("/titles/en").asText());
+ assertEquals(n.at("/resourceId").asText(), "WPD17");
+ assertEquals(n.at("/titles/de").asText(), "Deutsche Wikipedia Artikel 2017");
+ assertEquals(n.at("/titles/en").asText(), "German Wikipedia Articles 2017");
assertEquals(1, n.at("/languages").size());
assertEquals(6, n.at("/layers").size());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
index dc9dcaa..10891d0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/IndexControllerTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import java.net.URI;
@@ -9,16 +9,15 @@
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import org.apache.http.HttpStatus;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
@@ -31,7 +30,6 @@
/**
* @author margaretha
- *
*/
public class IndexControllerTest extends SpringJerseyTest {
@@ -39,10 +37,8 @@
private SearchKrill searchKrill;
@Test
- public void testCloseIndex () throws IOException, KustvaktException,
- URISyntaxException, InterruptedException {
- URI uri = IndexControllerTest.class.getClassLoader()
- .getResource("vc/named-vc1.jsonld").toURI();
+ public void testCloseIndex() throws IOException, KustvaktException, URISyntaxException, InterruptedException {
+ URI uri = IndexControllerTest.class.getClassLoader().getResource("vc/named-vc1.jsonld").toURI();
Path toLink = Paths.get(uri);
Path symLink = Paths.get("vc/named-vc1.jsonld");
Path vcPath = Paths.get("vc");
@@ -53,41 +49,19 @@
Files.delete(symLink);
}
Files.createSymbolicLink(symLink, toLink);
-
searchKrill.getStatistics(null);
assertEquals(true, searchKrill.getIndex().isReaderOpen());
-
Form form = new Form();
form.param("token", "secret");
-
- Response response = target().path(API_VERSION).path("index")
- .path("close")
- .request()
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("index").path("close").request().post(Entity.form(form));
assertEquals(HttpStatus.SC_OK, response.getStatus());
assertEquals(false, searchKrill.getIndex().isReaderOpen());
-
-
// Cleaning database and cache
-
Thread.sleep(200);
-
- response = target().path(API_VERSION).path("vc").path("~system")
- .path("named-vc1")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .delete();
-
- response = target().path(API_VERSION).path("vc").path("~system")
- .path("named-vc1")
- .request()
- .get();
-
+ response = target().path(API_VERSION).path("vc").path("~system").path("named-vc1").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).delete();
+ response = target().path(API_VERSION).path("vc").path("~system").path("named-vc1").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
index 113fe5b..3d5e3f1 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/InfoControllerTest.java
@@ -1,11 +1,11 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -21,28 +21,20 @@
@Autowired
private KustvaktConfiguration config;
+
@Autowired
private SearchKrill krill;
@Test
- public void testInfo () throws KustvaktException {
- Response response = target().path(API_VERSION).path("info")
- .request()
- .get();
-
+ public void testInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("info").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(config.getCurrentVersion(),
- node.at("/latest_api_version").asText());
- assertEquals(config.getSupportedVersions().size(),
- node.at("/supported_api_versions").size());
-
- assertEquals(ServiceInfo.getInfo().getVersion(),
- node.at("/kustvakt_version").asText());
- assertEquals(krill.getIndex().getVersion(),
- node.at("/krill_version").asText());
+ assertEquals(config.getCurrentVersion(), node.at("/latest_api_version").asText());
+ assertEquals(config.getSupportedVersions().size(), node.at("/supported_api_versions").size());
+ assertEquals(ServiceInfo.getInfo().getVersion(), node.at("/kustvakt_version").asText());
+ assertEquals(krill.getIndex().getVersion(), node.at("/krill_version").asText());
QuerySerializer s = new QuerySerializer();
assertEquals(s.getVersion(), node.at("/koral_version").asText());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
index efe1faf..85745aa 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MatchInfoControllerTest.java
@@ -1,13 +1,13 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -21,118 +21,55 @@
public class MatchInfoControllerTest extends SpringJerseyTest {
@Test
- public void testGetMatchInfoPublicCorpus () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGA").path("01784").path("p36-100")
- .path("matchInfo").queryParam("foundry", "*")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetMatchInfoPublicCorpus() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").path("p36-100").path("matchInfo").queryParam("foundry", "*").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertNotNull(node);
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- assertEquals("Goethe, Johann Wolfgang von",
- node.at("/author").asText());
- assertTrue(node.at("/snippet").asText()
- .startsWith("<span class=\"context-left\"></span>"
- + "<span class=\"match\">"));
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ assertEquals(node.at("/author").asText(), "Goethe, Johann Wolfgang von");
+ assertTrue(node.at("/snippet").asText().startsWith("<span class=\"context-left\"></span>" + "<span class=\"match\">"));
}
@Test
- public void testGetMatchInfoNotAllowed () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGI").path("04846").path("p36875-36876")
- .path("matchInfo").queryParam("foundry", "*")
- .request()
- .get();
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ public void testGetMatchInfoNotAllowed() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").path("p36875-36876").path("matchInfo").queryParam("foundry", "*").request().get();
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Retrieving resource with ID "
- + "match-GOE/AGI/04846-p36875-36876 is not allowed.",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Retrieving resource with ID " + "match-GOE/AGI/04846-p36875-36876 is not allowed.", node.at("/errors/0/1").asText());
assertTrue(node.at("/snippet").isMissingNode());
}
@Test
- public void testGetMatchInfoWithAuthentication () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGI").path("04846").path("p36875-36876")
- .path("matchInfo").queryParam("foundry", "*")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
- .get();
-
+ public void testGetMatchInfoWithAuthentication() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").path("p36875-36876").path("matchInfo").queryParam("foundry", "*").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
String entity = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
- assertEquals("GOE/AGI/04846", node.at("/textSigle").asText());
- assertEquals("Zweiter römischer Aufenthalt",
- node.at("/title").asText());
- assertEquals("vom Juni 1787 bis April 1788",
- node.at("/subTitle").asText());
- assertEquals("Goethe, Johann Wolfgang von",
- node.at("/author").asText());
- assertTrue(node.at("/snippet").asText()
- .startsWith("<span class=\"context-left\"></span>"
- + "<span class=\"match\">"));
- assertEquals("QAO-NC-LOC:ids", node.at("/availability").asText());
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGI/04846");
+ assertEquals(node.at("/title").asText(), "Zweiter römischer Aufenthalt");
+ assertEquals(node.at("/subTitle").asText(), "vom Juni 1787 bis April 1788");
+ assertEquals(node.at("/author").asText(), "Goethe, Johann Wolfgang von");
+ assertTrue(node.at("/snippet").asText().startsWith("<span class=\"context-left\"></span>" + "<span class=\"match\">"));
+ assertEquals(node.at("/availability").asText(), "QAO-NC-LOC:ids");
}
@Test
- public void testAvailabilityAll () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGD").path("00000").path("p75-76")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32")
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testAvailabilityAll() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").path("p75-76").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testAvailabilityAllUnauthorized () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGD").path("00000").path("p75-76")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32")
- .get();
-
+ public void testAvailabilityAllUnauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").path("p75-76").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Retrieving resource with ID "
- + "match-GOE/AGD/00000-p75-76 is not allowed.",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Retrieving resource with ID " + "match-GOE/AGD/00000-p75-76 is not allowed.", node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
index 5fab35d..bfa59e7 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MetadataControllerTest.java
@@ -1,13 +1,13 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -21,132 +21,64 @@
public class MetadataControllerTest extends SpringJerseyTest {
@Test
- public void testRetrieveMetadataWithField () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGA").path("01784")
- .queryParam("fields", "author")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testRetrieveMetadataWithField() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").queryParam("fields", "author").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("author", node.at("/document/fields/0/key").asText());
+ assertEquals(node.at("/document/fields/0/key").asText(), "author");
}
-
@Test
- public void testRetrieveMetadataWithMultipleFields () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGA").path("01784")
- .queryParam("fields", "author,title")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testRetrieveMetadataWithMultipleFields() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").queryParam("fields", "author,title").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
+ assertEquals(node.at("/document/fields/0/key").asText(), "author");
+ assertEquals(node.at("/document/fields/1/key").asText(), "title");
+ }
- assertEquals("author", node.at("/document/fields/0/key").asText());
- assertEquals("title", node.at("/document/fields/1/key").asText());
- }
-
@Test
- public void testFreeMetadata () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGA").path("01784")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testFreeMetadata() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGA").path("01784").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertTrue(!node.at("/document").isMissingNode());
-
}
// EM: currently all metadata are allowed
@Test
- @Ignore
- public void testMetadataUnauthorized () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGI").path("04846")
- .request()
- .get();
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ @Disabled
+ public void testMetadataUnauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").request().get();
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Retrieving resource with ID "
- + "GOE/AGI/04846 is not allowed.",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Retrieving resource with ID " + "GOE/AGI/04846 is not allowed.", node.at("/errors/0/1").asText());
}
@Test
- public void testMetadataWithAuthentication () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGI").path("04846")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMetadataWithAuthentication() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("04846").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testMetadataAvailabilityAll () throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGI").path("00000")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32")
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMetadataAvailabilityAll() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGI").path("00000").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
// EM: currently all metadata are allowed
@Test
- @Ignore
- public void testMetadataAvailabilityAllUnauthorized ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus")
- .path("GOE").path("AGD").path("00000")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32")
- .get();
-
+ @Disabled
+ public void testMetadataAvailabilityAllUnauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").path("AGD").path("00000").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "170.27.0.32").get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Retrieving resource with ID "
- + "GOE/AGD/00000 is not allowed.",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Retrieving resource with ID " + "GOE/AGD/00000 is not allowed.", node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
index f44c1c8..4ec1fe8 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/MultipleCorpusQueryTest.java
@@ -1,11 +1,11 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -18,72 +18,47 @@
public class MultipleCorpusQueryTest extends SpringJerseyTest {
@Test
- public void testSearchGet () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "das").queryParam("ql", "poliqarp")
- .queryParam("cq", "pubPlace=München")
- .queryParam("cq", "textSigle=\"GOE/AGA/01784\"")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchGet() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "das").queryParam("ql", "poliqarp").queryParam("cq", "pubPlace=München").queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
node = node.at("/collection/operands/1");
- assertEquals("koral:docGroup", node.at("/@type").asText());
- assertEquals("operation:and", node.at("/operation").asText());
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/operation").asText(), "operation:and");
assertEquals(2, node.at("/operands").size());
- assertEquals("koral:doc", node.at("/operands/0/@type").asText());
- assertEquals("match:eq", node.at("/operands/0/match").asText());
- assertEquals("pubPlace", node.at("/operands/0/key").asText());
- assertEquals("München", node.at("/operands/0/value").asText());
- assertEquals("textSigle", node.at("/operands/1/key").asText());
- assertEquals("GOE/AGA/01784", node.at("/operands/1/value").asText());
+ assertEquals(node.at("/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/0/key").asText(), "pubPlace");
+ assertEquals(node.at("/operands/0/value").asText(), "München");
+ assertEquals(node.at("/operands/1/key").asText(), "textSigle");
+ assertEquals(node.at("/operands/1/value").asText(), "GOE/AGA/01784");
}
@Test
- public void testStatisticsWithMultipleCq ()
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics").queryParam("cq", "textType=Abhandlung")
- .queryParam("cq", "corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithMultipleCq() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung").queryParam("cq", "corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
@Test
- public void testStatisticsWithMultipleCorpusQuery ()
- throws ProcessingException,
- KustvaktException {
- Response response =
- target().path(API_VERSION).path("statistics")
- .queryParam("corpusQuery", "textType=Autobiographie")
- .queryParam("corpusQuery", "corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithMultipleCorpusQuery() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie").queryParam("corpusQuery", "corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(9, node.at("/documents").asInt());
assertEquals(527662, node.at("/tokens").asInt());
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
-
- assertEquals(StatusCodes.DEPRECATED,
- node.at("/warnings/0/0").asInt());
- assertEquals("Parameter corpusQuery is deprecated in favor of cq.",
- node.at("/warnings/0/1").asText());
+ assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
index e5abc6a..ed61f10 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AccessTokenTest.java
@@ -1,11 +1,10 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
@@ -13,11 +12,9 @@
import org.apache.http.entity.ContentType;
import org.apache.oltu.oauth2.common.message.types.GrantType;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.OAuth2Scope;
@@ -29,69 +26,47 @@
public class OAuth2AccessTokenTest extends OAuth2TestBase {
private String userAuthHeader;
+
private String clientAuthHeader;
- public OAuth2AccessTokenTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
- clientAuthHeader =
- HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(
- confidentialClientId, clientSecret);
+ public OAuth2AccessTokenTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
+ clientAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(confidentialClientId, clientSecret);
}
@Test
- public void testScopeWithSuperClient () throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(superClientId, clientSecret);
-
+ public void testScopeWithSuperClient() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals("all", node.at("/scope").asText());
+ assertEquals(node.at("/scope").asText(), "all");
String accessToken = node.at("/access_token").asText();
-
// test list user group
- response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .get();
-
+ response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(2, node.size());
}
@Test
- public void testCustomScope () throws KustvaktException {
- Response response =
- requestAuthorizationCode("code", confidentialClientId, "",
- OAuth2Scope.VC_INFO.toString(), "", userAuthHeader);
+ public void testCustomScope() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", OAuth2Scope.VC_INFO.toString(), "", userAuthHeader);
String code = parseAuthorizationCode(response);
-
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
-
String token = node.at("/access_token").asText();
- assertTrue(node.at("/scope").asText()
- .contains(OAuth2Scope.VC_INFO.toString()));
-
+ assertTrue(node.at("/scope").asText().contains(OAuth2Scope.VC_INFO.toString()));
// test list vc using the token
- response = target().path(API_VERSION).path("vc")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + token)
- .get();
-
+ response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + token).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(4, node.size());
}
@Test
- public void testDefaultScope () throws KustvaktException, IOException {
+ public void testDefaultScope() throws KustvaktException, IOException {
String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
testScopeNotAuthorized(accessToken);
@@ -99,91 +74,52 @@
testSearchWithOAuth2Token(accessToken);
}
- private void testScopeNotAuthorized (String accessToken)
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .get();
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ private void testScopeNotAuthorized(String accessToken) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Scope vc_info is not authorized",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Scope vc_info is not authorized");
}
- private void testScopeNotAuthorize2 (String accessToken)
- throws KustvaktException {
- Response response =
- target().path(API_VERSION).path("vc").path("access")
- .request()
- .header(Attributes.AUTHORIZATION,
- "Bearer " + accessToken)
- .get();
+ private void testScopeNotAuthorize2(String accessToken) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
String entity = response.readEntity(String.class);
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Scope vc_access_info is not authorized",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Scope vc_access_info is not authorized");
}
@Test
- public void testSearchWithUnknownToken ()
- throws KustvaktException, IOException {
- Response response =
- searchWithAccessToken("ljsa8tKNRSczJhk20öhq92zG8z350");
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithUnknownToken() throws KustvaktException, IOException {
+ Response response = searchWithAccessToken("ljsa8tKNRSczJhk20öhq92zG8z350");
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
- assertEquals("Access token is invalid",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
}
@Test
- public void testRevokeAccessTokenConfidentialClient ()
- throws KustvaktException {
- String code = requestAuthorizationCode(confidentialClientId,
- userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
- confidentialClientId, code, clientAuthHeader);
-
+ public void testRevokeAccessTokenConfidentialClient() throws KustvaktException {
+ String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
String accessToken = node.at("/access_token").asText();
Form form = new Form();
form.param("token", accessToken);
form.param("client_id", confidentialClientId);
form.param("client_secret", "secret");
-
- Response response = target().path(API_VERSION).path("oauth2").path("revoke")
- .request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("revoke").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testSearchWithRevokedAccessToken(accessToken);
}
-
+
@Test
- public void testRevokeAccessTokenPublicClientViaSuperClient()
- throws KustvaktException {
- String code = requestAuthorizationCode(publicClientId,
- userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, "", code);
-
+ public void testRevokeAccessTokenPublicClientViaSuperClient() throws KustvaktException {
+ String code = requestAuthorizationCode(publicClientId, userAuthHeader);
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
testRevokeTokenViaSuperClient(accessToken, userAuthHeader);
@@ -191,77 +127,47 @@
}
@Test
- public void testAccessTokenAfterRequestRefreshToken ()
- throws KustvaktException, IOException {
- String code =
- requestAuthorizationCode(confidentialClientId, userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
- confidentialClientId, code, clientAuthHeader);
-
+ public void testAccessTokenAfterRequestRefreshToken() throws KustvaktException, IOException {
+ String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
String accessToken = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
-
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", confidentialClientId);
form.param("client_secret", "secret");
form.param("refresh_token", refreshToken);
-
- Response response = target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertTrue(!refreshToken.equals(node.at("/refresh_token").asText()));
-
testSearchWithRevokedAccessToken(accessToken);
}
@Test
- public void testRequestAuthorizationWithBearerTokenUnauthorized ()
- throws KustvaktException {
- String code = requestAuthorizationCode(confidentialClientId,
- userAuthHeader);
- JsonNode node = requestTokenWithAuthorizationCodeAndHeader(
- confidentialClientId, code, clientAuthHeader);
+ public void testRequestAuthorizationWithBearerTokenUnauthorized() throws KustvaktException {
+ String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
+ JsonNode node = requestTokenWithAuthorizationCodeAndHeader(confidentialClientId, code, clientAuthHeader);
String userAuthToken = node.at("/access_token").asText();
-
- Response response = requestAuthorizationCode("code",
- confidentialClientId, "", "search", "", "Bearer " + userAuthToken);
-
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", "search", "", "Bearer " + userAuthToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Scope authorize is not authorized",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Scope authorize is not authorized");
}
@Test
- public void testRequestAuthorizationWithBearerToken ()
- throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(superClientId, clientSecret);
+ public void testRequestAuthorizationWithBearerToken() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
String userAuthToken = node.at("/access_token").asText();
assertNotNull(userAuthToken);
- assertEquals(TokenType.BEARER.displayName(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.displayName(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
-
- String code = requestAuthorizationCode(superClientId,
- "Bearer " + userAuthToken);
+ String code = requestAuthorizationCode(superClientId, "Bearer " + userAuthToken);
assertNotNull(code);
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
index c8d15b9..a4fed9b 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AdminControllerTest.java
@@ -1,21 +1,7 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-import javax.ws.rs.ProcessingException;
-import javax.ws.rs.client.Entity;
-import javax.ws.rs.core.Form;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.Status;
-
-import org.apache.http.entity.ContentType;
-import org.junit.Test;
-import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -23,197 +9,144 @@
import de.ids_mannheim.korap.oauth2.dao.AccessTokenDao;
import de.ids_mannheim.korap.oauth2.dao.RefreshTokenDao;
import de.ids_mannheim.korap.utils.JsonUtils;
+import org.apache.http.entity.ContentType;
+import org.junit.jupiter.api.Order;
+import org.junit.jupiter.api.Test;
+import org.springframework.beans.factory.annotation.Autowired;
+import javax.ws.rs.ProcessingException;
+import javax.ws.rs.client.Entity;
+import javax.ws.rs.core.Form;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+@Order(Integer.MAX_VALUE) // make sure this runs as last test as it removes tokens
public class OAuth2AdminControllerTest extends OAuth2TestBase {
private String username = "OAuth2AdminControllerTest";
+
private String adminAuthHeader;
+
private String userAuthHeader;
@Autowired
private RefreshTokenDao refreshDao;
+
@Autowired
private AccessTokenDao accessDao;
- public OAuth2AdminControllerTest () throws KustvaktException {
- adminAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "password");
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2AdminControllerTest() throws KustvaktException {
+ adminAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "password");
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
}
- private Response updateClientPrivilege (String username,
- Form form)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("admin")
- .path("oauth2").path("client").path("privilege")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ private Response updateClientPrivilege(String username, Form form) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin").path("oauth2").path("client").path("privilege").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
return response;
}
-
- private Response updateClientPrivilegeWithAdminToken (String clientId)
- throws ProcessingException,
- KustvaktException {
-
+
+ private Response updateClientPrivilegeWithAdminToken(String clientId) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
form.param("super", Boolean.toString(false));
- form.param("token", "secret"); //adminToken
-
- Response response = target().path(API_VERSION).path("admin")
- .path("oauth2").path("client").path("privilege")
- .request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ // adminToken
+ form.param("token", "secret");
+ Response response = target().path(API_VERSION).path("admin").path("oauth2").path("client").path("privilege").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
return response;
}
-
-
- private void testUpdateClientPriviledgeUnauthorized (Form form)
- throws ProcessingException, KustvaktException {
+
+ private void testUpdateClientPriviledgeUnauthorized(Form form) throws ProcessingException, KustvaktException {
Response response = updateClientPrivilege(username, form);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testCleanExpiredTokensUsingAdminToken () throws KustvaktException {
+ public void testCleanExpiredTokensUsingAdminToken() throws KustvaktException {
createExpiredAccessToken();
int refreshTokensBefore =
refreshDao.retrieveInvalidRefreshTokens().size();
- assertTrue(refreshTokensBefore > 0);
+ assertTrue(refreshTokensBefore > 0);
int accessTokensBefore = accessDao.retrieveInvalidAccessTokens().size();
assertTrue(accessTokensBefore > 0);
-
Form form = new Form();
form.param("token", "secret");
-
- target().path(API_VERSION).path("admin").path("oauth2").path("token")
- .path("clean")
- .request()
- .post(Entity.form(form));
-
+ target().path(API_VERSION).path("admin").path("oauth2").path("token").path("clean").request().post(Entity.form(form));
assertEquals(0, refreshDao.retrieveInvalidRefreshTokens().size());
assertEquals(0, accessDao.retrieveInvalidAccessTokens().size());
}
@Test
- public void testCleanRevokedTokens () throws KustvaktException {
-
+ public void testCleanRevokedTokens() throws KustvaktException {
int accessTokensBefore = accessDao.retrieveInvalidAccessTokens().size();
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
-
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
String accessToken = node.at("/access_token").asText();
testRevokeToken(accessToken, publicClientId, null, ACCESS_TOKEN_TYPE);
-
int accessTokensAfter = accessDao.retrieveInvalidAccessTokens().size();
assertEquals(accessTokensAfter, accessTokensBefore + 1);
-
- target().path(API_VERSION).path("admin").path("oauth2").path("token")
- .path("clean")
- .request()
- .header(Attributes.AUTHORIZATION, adminAuthHeader)
- .post(null);
-
+ target().path(API_VERSION).path("admin").path("oauth2").path("token").path("clean").request().header(Attributes.AUTHORIZATION, adminAuthHeader).post(null);
assertEquals(0, accessDao.retrieveInvalidAccessTokens().size());
}
@Test
- public void testUpdateClientPrivilege () throws KustvaktException {
+ public void testUpdateClientPrivilege() throws KustvaktException {
// register a client
Response response = registerConfidentialClient(username);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
-
// request an access token
- String clientAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(clientId, clientSecret);
+ String clientAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(clientId, clientSecret);
String code = requestAuthorizationCode(clientId, userAuthHeader);
- node = requestTokenWithAuthorizationCodeAndHeader(clientId, code,
- clientAuthHeader);
+ node = requestTokenWithAuthorizationCodeAndHeader(clientId, code, clientAuthHeader);
String accessToken = node.at("/access_token").asText();
-
- //update client priviledge to super client
+ // update client priviledge to super client
Form form = new Form();
form.param("client_id", clientId);
form.param("super", Boolean.toString(true));
-
testUpdateClientPriviledgeUnauthorized(form);
-
response = updateClientPrivilege("admin", form);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testAccessTokenAfterUpgradingClient(clientId, accessToken);
-
// degrade a super client to a common client
-
updateClientPrivilegeWithAdminToken(clientId);
-
testAccessTokenAfterDegradingSuperClient(clientId, accessToken);
-
deregisterClient(username, clientId);
}
// old access tokens retain their scopes
- private void testAccessTokenAfterUpgradingClient (String clientId,
- String accessToken) throws KustvaktException {
-
+ private void testAccessTokenAfterUpgradingClient(String clientId, String accessToken) throws KustvaktException {
JsonNode node = retrieveClientInfo(clientId, "admin");
assertTrue(node.at("/super").asBoolean());
-
// list vc
- Response response = target().path(API_VERSION).path("vc")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .get();
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("vc").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Scope vc_info is not authorized",
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Scope vc_info is not authorized");
// search
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testAccessTokenAfterDegradingSuperClient (String clientId,
- String accessToken) throws KustvaktException {
+ private void testAccessTokenAfterDegradingSuperClient(String clientId, String accessToken) throws KustvaktException {
JsonNode node = retrieveClientInfo(clientId, username);
assertTrue(node.at("/isSuper").isMissingNode());
-
Response response = searchWithAccessToken(accessToken);
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
- assertEquals("Access token is invalid",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
index 0427ac7..732d8c1 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2AuthorizationPostTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.net.URI;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MultivaluedMap;
@@ -14,13 +13,11 @@
import org.apache.http.entity.ContentType;
import org.apache.oltu.oauth2.common.message.types.TokenType;
import org.glassfish.jersey.uri.UriComponent;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -30,71 +27,47 @@
public String userAuthHeader;
- public OAuth2AuthorizationPostTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2AuthorizationPostTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
}
-
- private Response requestAuthorizationCode (
- Form form, String authHeader)
- throws KustvaktException {
- return target().path(API_VERSION).path("oauth2").path("authorize")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ private Response requestAuthorizationCode(Form form, String authHeader) throws KustvaktException {
+ return target().path(API_VERSION).path("oauth2").path("authorize").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
}
-
+
@Test
- public void testAuthorizeConfidentialClient () throws KustvaktException {
+ public void testAuthorizeConfidentialClient() throws KustvaktException {
Form form = new Form();
form.param("response_type", "code");
form.param("client_id", confidentialClientId);
form.param("state", "thisIsMyState");
form.param("scope", "search");
-
- Response response =
- requestAuthorizationCode(form, userAuthHeader);
-
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
+ Response response = requestAuthorizationCode(form, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
- MultiValueMap<String, String> params = UriComponentsBuilder
- .fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
assertNotNull(params.getFirst("code"));
- assertEquals("thisIsMyState", params.getFirst("state"));
+ assertEquals(params.getFirst("state"), "thisIsMyState");
}
-
- @Test
- public void testRequestTokenAuthorizationConfidential ()
- throws KustvaktException {
+ @Test
+ public void testRequestTokenAuthorizationConfidential() throws KustvaktException {
Form authForm = new Form();
authForm.param("response_type", "code");
authForm.param("client_id", confidentialClientId);
authForm.param("scope", "search");
-
- Response response =
- requestAuthorizationCode(authForm, userAuthHeader);
+ Response response = requestAuthorizationCode(authForm, userAuthHeader);
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- UriComponent.decodeQuery(redirectUri, true);
+ MultivaluedMap<String, String> params = UriComponent.decodeQuery(redirectUri, true);
String code = params.get("code").get(0);
String scopes = params.get("scope").get(0);
-
assertEquals(scopes, "search");
-
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
index 554d184..d210ffd 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ClientControllerTest.java
@@ -1,9 +1,9 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.io.InputStream;
@@ -11,7 +11,6 @@
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
-
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
@@ -22,11 +21,9 @@
import org.apache.http.entity.ContentType;
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.glassfish.jersey.server.ContainerRequest;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -38,32 +35,27 @@
/**
* @author margaretha
- *
*/
public class OAuth2ClientControllerTest extends OAuth2TestBase {
private String username = "OAuth2ClientControllerTest";
+
private String userAuthHeader;
- public OAuth2ClientControllerTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2ClientControllerTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
}
- private void checkWWWAuthenticateHeader (Response response) {
- Set<Entry<String, List<Object>>> headers =
- response.getHeaders().entrySet();
-
+ private void checkWWWAuthenticateHeader(Response response) {
+ Set<Entry<String, List<Object>>> headers = response.getHeaders().entrySet();
for (Entry<String, List<Object>> header : headers) {
if (header.getKey().equals(ContainerRequest.WWW_AUTHENTICATE)) {
- assertEquals("Basic realm=\"Kustvakt\"",
- header.getValue().get(0));
+ assertEquals(header.getValue().get(0), "Basic realm=\"Kustvakt\"");
}
}
}
- private OAuth2ClientJson createOAuth2ClientJson (String name,
- OAuth2ClientType type, String description) {
+ private OAuth2ClientJson createOAuth2ClientJson(String name, OAuth2ClientType type, String description) {
OAuth2ClientJson client = new OAuth2ClientJson();
if (name != null) {
client.setName(name);
@@ -73,44 +65,38 @@
client.setDescription(description);
}
return client;
-
}
@Test
- public void testRetrieveClientInfo () throws KustvaktException {
+ public void testRetrieveClientInfo() throws KustvaktException {
// public client
JsonNode clientInfo = retrieveClientInfo(publicClientId, "system");
assertEquals(publicClientId, clientInfo.at("/client_id").asText());
- assertEquals("public client plugin with redirect uri",
- clientInfo.at("/client_name").asText());
+ assertEquals(clientInfo.at("/client_name").asText(), "public client plugin with redirect uri");
assertNotNull(clientInfo.at("/client_description"));
assertNotNull(clientInfo.at("/client_url"));
- assertEquals("PUBLIC", clientInfo.at("/client_type").asText());
- assertEquals("system", clientInfo.at("/registered_by").asText());
-
+ assertEquals(clientInfo.at("/client_type").asText(), "PUBLIC");
+ assertEquals(clientInfo.at("/registered_by").asText(), "system");
// confidential client
clientInfo = retrieveClientInfo(confidentialClientId, "system");
assertEquals(confidentialClientId, clientInfo.at("/client_id").asText());
- assertEquals("non super confidential client",
- clientInfo.at("/client_name").asText());
+ assertEquals(clientInfo.at("/client_name").asText(), "non super confidential client");
assertNotNull(clientInfo.at("/client_url"));
assertNotNull(clientInfo.at("/redirect_uri"));
assertEquals(false, clientInfo.at("/super").asBoolean());
- assertEquals("CONFIDENTIAL", clientInfo.at("/client_type").asText());
-
+ assertEquals(clientInfo.at("/client_type").asText(), "CONFIDENTIAL");
// super client
clientInfo = retrieveClientInfo(superClientId, "system");
assertEquals(superClientId, clientInfo.at("/client_id").asText());
- assertEquals("super confidential client",
- clientInfo.at("/client_name").asText());
+ assertEquals(clientInfo.at("/client_name").asText(), "super confidential client");
assertNotNull(clientInfo.at("/client_url"));
assertNotNull(clientInfo.at("/redirect_uri"));
- assertEquals("CONFIDENTIAL", clientInfo.at("/client_type").asText());
+ assertEquals(clientInfo.at("/client_type").asText(), "CONFIDENTIAL");
assertTrue(clientInfo.at("/super").asBoolean());
}
-
+
@Test
- public void testRegisterConfidentialClient () throws KustvaktException {
+ public void testRegisterConfidentialClient() throws KustvaktException {
Response response = registerConfidentialClient(username);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
@@ -120,686 +106,429 @@
assertNotNull(clientId);
assertNotNull(clientSecret);
assertFalse(clientId.contains("a"));
-
testListConfidentialClient(username, clientId);
testConfidentialClientInfo(clientId, username);
testResetConfidentialClientSecret(clientId, clientSecret);
deregisterClient(username, clientId);
}
-
- @Test
- public void testRegisterClientNameTooShort ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("R", OAuth2ClientType.PUBLIC, null);
+ @Test
+ public void testRegisterClientNameTooShort() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R", OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("client_name must contain at least 3 characters",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "client_name must contain at least 3 characters");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientEmptyName ()
- throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("", OAuth2ClientType.PUBLIC, null);
-
+ public void testRegisterClientEmptyName() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("", OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("client_name must contain at least 3 characters",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "client_name must contain at least 3 characters");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingName ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson(null, OAuth2ClientType.PUBLIC, null);
-
+ public void testRegisterClientMissingName() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson(null, OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("client_name is null",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "client_name is null");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingDescription ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R client",
- OAuth2ClientType.PUBLIC, null);
-
+ public void testRegisterClientMissingDescription() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", OAuth2ClientType.PUBLIC, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("client_description is null",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "client_description is null");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientMissingType ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("R client", null, null);
-
+ public void testRegisterClientMissingType() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", null, null);
Response response = registerClient(username, clientJson);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("client_type is null",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "client_type is null");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-
+
@Test
- public void testRegisterClientInvalidRedirectURI ()
- throws ProcessingException,
- KustvaktException {
+ public void testRegisterClientInvalidRedirectURI() throws ProcessingException, KustvaktException {
// invalid hostname
String redirectUri = "https://test.public.client/redirect";
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2PublicClient",
- OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
clientJson.setRedirectURI(redirectUri);
Response response = registerClient(username, clientJson);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),false,
- response.getStatus());
-
+ testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), false, response.getStatus());
// localhost is not allowed
-// redirectUri = "http://localhost:1410";
-// clientJson.setRedirectURI(redirectUri);
-// response = registerClient(username, clientJson);
-// testInvalidRedirectUri(response.readEntity(String.class), false,
-// response.getStatus());
-
+ // redirectUri = "http://localhost:1410";
+ // clientJson.setRedirectURI(redirectUri);
+ // response = registerClient(username, clientJson);
+ // testInvalidRedirectUri(response.readEntity(String.class), false,
+ // response.getStatus());
// fragment is not allowed
redirectUri = "https://public.client.com/redirect.html#bar";
clientJson.setRedirectURI(redirectUri);
response = registerClient(username, clientJson);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),false,
- response.getStatus());
+ testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), false, response.getStatus());
}
-
+
@Test
- public void testRegisterPublicClientWithRefreshTokenExpiry ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2PublicClient",
- OAuth2ClientType.PUBLIC, "A public test client.");
+ public void testRegisterPublicClientWithRefreshTokenExpiry() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
clientJson.setRefreshTokenExpiry(31535000);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-
+
@Test
- public void testRegisterConfidentialClientWithRefreshTokenExpiry ()
- throws ProcessingException,
- KustvaktException {
+ public void testRegisterConfidentialClientWithRefreshTokenExpiry() throws ProcessingException, KustvaktException {
int expiry = 31535000;
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2 Confidential Client",
- OAuth2ClientType.CONFIDENTIAL, "A confidential client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL, "A confidential client.");
clientJson.setRefreshTokenExpiry(expiry);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String clientId = node.at("/client_id").asText();
JsonNode clientInfo = retrieveClientInfo(clientId, username);
assertEquals(expiry, clientInfo.at("/refresh_token_expiry").asInt());
-
deregisterClient(username, clientId);
}
-
+
@Test
- public void testRegisterConfidentialClientWithInvalidRefreshTokenExpiry ()
- throws ProcessingException,
- KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson(
- "OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL,
- "A confidential client.");
+ public void testRegisterConfidentialClientWithInvalidRefreshTokenExpiry() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2 Confidential Client", OAuth2ClientType.CONFIDENTIAL, "A confidential client.");
clientJson.setRefreshTokenExpiry(31537000);
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(
- "Maximum refresh token expiry is 31536000 seconds (1 year)",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Maximum refresh token expiry is 31536000 seconds (1 year)");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-
+
@Test
- public void testRegisterClientInvalidURL ()
- throws ProcessingException,
- KustvaktException {
+ public void testRegisterClientInvalidURL() throws ProcessingException, KustvaktException {
// invalid hostname
String url = "https://test.public.client";
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2PublicClient",
- OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
clientJson.setUrl(url);
Response response = registerClient(username, clientJson);
testInvalidUrl(response.readEntity(String.class), response.getStatus());
-
// localhost is not allowed
url = "http://localhost:1410";
clientJson.setRedirectURI(url);
response = registerClient(username, clientJson);
testInvalidUrl(response.readEntity(String.class), response.getStatus());
}
-
- private void testInvalidUrl (String entity,
- int status) throws KustvaktException {
+
+ private void testInvalidUrl(String entity, int status) throws KustvaktException {
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.CodeResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Invalid URL",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.CodeResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid URL");
assertEquals(Status.BAD_REQUEST.getStatusCode(), status);
}
@Test
- public void testRegisterPublicClient ()
- throws ProcessingException, KustvaktException {
+ public void testRegisterPublicClient() throws ProcessingException, KustvaktException {
String redirectUri = "https://public.client.com/redirect";
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2PublicClient",
- OAuth2ClientType.PUBLIC, "A public test client.");
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2PublicClient", OAuth2ClientType.PUBLIC, "A public test client.");
// http and fragment are allowed
clientJson.setUrl("http://public.client.com/index.html#bar");
clientJson.setRedirectURI(redirectUri);
-
Response response = registerClient(username, clientJson);
-
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
-
testRegisterClientUnauthorizedScope(clientId);
testResetPublicClientSecret(clientId);
testAccessTokenAfterDeregistration(clientId, null, "");
}
- private void testRegisterClientUnauthorizedScope (String clientId)
- throws ProcessingException,
- KustvaktException {
-
- String userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
+ private void testRegisterClientUnauthorizedScope(String clientId) throws ProcessingException, KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
String code = requestAuthorizationCode(clientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- clientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
-
- assertEquals("match_info search", node.at("/scope").asText());
-
+ assertEquals(node.at("/scope").asText(), "match_info search");
String accessToken = node.at("/access_token").asText();
-
- OAuth2ClientJson clientJson = createOAuth2ClientJson("R client",
- OAuth2ClientType.PUBLIC, null);
-
- response = target().path(API_VERSION).path("oauth2").path("client")
- .path("register")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(Entity.json(clientJson));
-
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("R client", OAuth2ClientType.PUBLIC, null);
+ response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(clientJson));
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Scope register_client is not authorized",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Scope register_client is not authorized");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
@Test
- public void testRegisterClientUsingPlainJson ()
- throws ProcessingException,
- KustvaktException, IOException {
-
- InputStream is = getClass().getClassLoader()
- .getResourceAsStream("json/oauth2_public_client.json");
+ public void testRegisterClientUsingPlainJson() throws ProcessingException, KustvaktException, IOException {
+ InputStream is = getClass().getClassLoader().getResourceAsStream("json/oauth2_public_client.json");
String json = IOUtils.toString(is, Charset.defaultCharset());
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("register")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username,
- "password"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .post(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("register").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).post(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
-
testResetPublicClientSecret(clientId);
testAccessTokenAfterDeregistration(clientId, null, "");
}
@Test
- public void testRegisterDesktopApp ()
- throws ProcessingException, KustvaktException {
- OAuth2ClientJson clientJson = createOAuth2ClientJson(
- "OAuth2DesktopClient", OAuth2ClientType.PUBLIC,
- "This is a desktop test client.");
-
+ public void testRegisterDesktopApp() throws ProcessingException, KustvaktException {
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2DesktopClient", OAuth2ClientType.PUBLIC, "This is a desktop test client.");
Response response = registerClient(username, clientJson);
-
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId = node.at("/client_id").asText();
assertNotNull(clientId);
assertTrue(node.at("/client_secret").isMissingNode());
-
testDeregisterPublicClientMissingUserAuthentication(clientId);
testDeregisterPublicClientMissingId();
testDeregisterPublicClient(clientId, username);
}
@Test
- public void testRegisterMultipleDesktopApps ()
- throws ProcessingException,
- KustvaktException {
-
+ public void testRegisterMultipleDesktopApps() throws ProcessingException, KustvaktException {
// First client
- OAuth2ClientJson clientJson =
- createOAuth2ClientJson("OAuth2DesktopClient1",
- OAuth2ClientType.PUBLIC, "A desktop test client.");
-
+ OAuth2ClientJson clientJson = createOAuth2ClientJson("OAuth2DesktopClient1", OAuth2ClientType.PUBLIC, "A desktop test client.");
Response response = registerClient(username, clientJson);
-
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
String clientId1 = node.at("/client_id").asText();
assertNotNull(clientId1);
assertTrue(node.at("/client_secret").isMissingNode());
-
// Second client
- clientJson = createOAuth2ClientJson("OAuth2DesktopClient2",
- OAuth2ClientType.PUBLIC, "Another desktop test client.");
-
+ clientJson = createOAuth2ClientJson("OAuth2DesktopClient2", OAuth2ClientType.PUBLIC, "Another desktop test client.");
response = registerClient(username, clientJson);
-
entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(entity);
String clientId2 = node.at("/client_id").asText();
assertNotNull(clientId2);
assertTrue(node.at("/client_secret").isMissingNode());
-
testResetPublicClientSecret(clientId1);
- testAccessTokenAfterDeregistration(clientId1, null,
- "https://OAuth2DesktopClient1.com");
+ testAccessTokenAfterDeregistration(clientId1, null, "https://OAuth2DesktopClient1.com");
testResetPublicClientSecret(clientId2);
- testAccessTokenAfterDeregistration(clientId2, null,
- "https://OAuth2DesktopClient2.com");
+ testAccessTokenAfterDeregistration(clientId2, null, "https://OAuth2DesktopClient2.com");
}
- private void testAccessTokenAfterDeregistration (String clientId,
- String clientSecret, String redirectUri) throws KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
-
+ private void testAccessTokenAfterDeregistration(String clientId, String clientSecret, String redirectUri) throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
String code = requestAuthorizationCode(clientId, redirectUri, userAuthHeader);
-
- Response response = requestTokenWithAuthorizationCodeAndForm(
- clientId, clientSecret, code, redirectUri);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, redirectUri);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
-
response = searchWithAccessToken(accessToken);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
code = requestAuthorizationCode(clientId, redirectUri, userAuthHeader);
testDeregisterPublicClient(clientId, username);
-
- response = requestTokenWithAuthorizationCodeAndForm(clientId,
- clientSecret, code, redirectUri);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, redirectUri);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuth2Error.INVALID_CLIENT.toString(),
- node.at("/error").asText());
-
+ assertEquals(OAuth2Error.INVALID_CLIENT.toString(), node.at("/error").asText());
response = searchWithAccessToken(accessToken);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
- assertEquals("Access token is invalid",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
}
- private void testDeregisterPublicClientMissingUserAuthentication (
- String clientId) throws
- ProcessingException, KustvaktException {
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("deregister").path(clientId)
- .request()
- .delete();
-
+ private void testDeregisterPublicClientMissingUserAuthentication(String clientId) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").path(clientId).request().delete();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
}
- private void testDeregisterPublicClientMissingId ()
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("deregister")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
- assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(),
- response.getStatus());
+ private void testDeregisterPublicClientMissingId() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
+ assertEquals(Status.METHOD_NOT_ALLOWED.getStatusCode(), response.getStatus());
}
- private void testDeregisterPublicClient (String clientId, String username)
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("deregister").path(clientId)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ private void testDeregisterPublicClient(String clientId, String username) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("deregister").path(clientId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testResetPublicClientSecret (String clientId)
- throws ProcessingException,
- KustvaktException {
+ private void testResetPublicClientSecret(String clientId) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("reset")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("reset").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Operation is not allowed for public clients",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Operation is not allowed for public clients");
}
- private String testResetConfidentialClientSecret (String clientId,
- String clientSecret) throws
- ProcessingException, KustvaktException {
+ private String testResetConfidentialClientSecret(String clientId, String clientSecret) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("reset")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("reset").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(clientId, node.at("/client_id").asText());
-
String newClientSecret = node.at("/client_secret").asText();
assertTrue(!clientSecret.equals(newClientSecret));
-
return newClientSecret;
}
- private void requestAuthorizedClientList (String userAuthHeader)
- throws KustvaktException {
+ private void requestAuthorizedClientList(String userAuthHeader) throws KustvaktException {
Form form = getSuperClientForm();
form.param("authorized_only", "true");
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("client").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, userAuthHeader)
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("client").path("list").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
assertEquals(confidentialClientId, node.at("/0/client_id").asText());
assertEquals(publicClientId, node.at("/1/client_id").asText());
-
- assertEquals("non super confidential client",
- node.at("/0/client_name").asText());
- assertEquals("CONFIDENTIAL", node.at("/0/client_type").asText());
+ assertEquals(node.at("/0/client_name").asText(), "non super confidential client");
+ assertEquals(node.at("/0/client_type").asText(), "CONFIDENTIAL");
assertFalse(node.at("/0/client_url").isMissingNode());
assertFalse(node.at("/0/client_description").isMissingNode());
}
@Test
- public void testListPublicClient () throws KustvaktException {
+ public void testListPublicClient() throws KustvaktException {
String clientName = "OAuth2DoryClient";
- OAuth2ClientJson json = createOAuth2ClientJson(clientName,
- OAuth2ClientType.PUBLIC, "Dory's client.");
+ OAuth2ClientJson json = createOAuth2ClientJson(clientName, OAuth2ClientType.PUBLIC, "Dory's client.");
registerClient("dory", json);
-
JsonNode node = listUserRegisteredClients("dory");
assertEquals(1, node.size());
assertEquals(clientName, node.at("/0/client_name").asText());
- assertEquals(OAuth2ClientType.PUBLIC.name(),
- node.at("/0/client_type").asText());
+ assertEquals(OAuth2ClientType.PUBLIC.name(), node.at("/0/client_type").asText());
assertTrue(node.at("/0/permitted").asBoolean());
assertFalse(node.at("/0/registration_date").isMissingNode());
assertTrue(node.at("/refresh_token_expiry").isMissingNode());
-
String clientId = node.at("/0/client_id").asText();
testDeregisterPublicClient(clientId, "dory");
}
-
- private void testListConfidentialClient (String username, String clientId)
- throws ProcessingException,
- KustvaktException {
+
+ private void testListConfidentialClient(String username, String clientId) throws ProcessingException, KustvaktException {
JsonNode node = listUserRegisteredClients(username);
assertEquals(1, node.size());
assertEquals(clientId, node.at("/0/client_id").asText());
- assertEquals("OAuth2ClientTest", node.at("/0/client_name").asText());
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
- node.at("/0/client_type").asText());
+ assertEquals(node.at("/0/client_name").asText(), "OAuth2ClientTest");
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), node.at("/0/client_type").asText());
assertNotNull(node.at("/0/client_description"));
assertEquals(clientURL, node.at("/0/client_url").asText());
- assertEquals(clientRedirectUri,
- node.at("/0/client_redirect_uri").asText());
+ assertEquals(clientRedirectUri, node.at("/0/client_redirect_uri").asText());
assertNotNull(node.at("/0/registration_date"));
-
- assertEquals(defaultRefreshTokenExpiry,
- node.at("/0/refresh_token_expiry").asInt());
+ assertEquals(defaultRefreshTokenExpiry, node.at("/0/refresh_token_expiry").asInt());
assertTrue(node.at("/0/permitted").asBoolean());
assertTrue(node.at("/0/source").isMissingNode());
}
-
+
@Test
- public void testListUserClients () throws KustvaktException {
+ public void testListUserClients() throws KustvaktException {
String username = "pearl";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, password);
-
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
// super client
- Response response = requestTokenWithPassword(superClientId,
- clientSecret, username, password);
+ Response response = requestTokenWithPassword(superClientId, clientSecret, username, password);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// client 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "",
- code);
+ response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
-
// client 2
code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
String refreshToken = node.at("/refresh_token").asText();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
requestAuthorizedClientList(userAuthHeader);
testListAuthorizedClientWithMultipleRefreshTokens(userAuthHeader);
testListAuthorizedClientWithMultipleAccessTokens(userAuthHeader);
testListWithClientsFromAnotherUser(userAuthHeader);
-
// revoke client 1
- testRevokeAllTokenViaSuperClient(publicClientId, userAuthHeader,
- accessToken);
-
+ testRevokeAllTokenViaSuperClient(publicClientId, userAuthHeader, accessToken);
// revoke client 2
node = JsonUtils.readTree(response.readEntity(String.class));
accessToken = node.at("/access_token").asText();
refreshToken = node.at("/refresh_token").asText();
- testRevokeAllTokenViaSuperClient(confidentialClientId, userAuthHeader,
- accessToken);
- testRequestTokenWithRevokedRefreshToken(confidentialClientId,
- clientSecret, refreshToken);
+ testRevokeAllTokenViaSuperClient(confidentialClientId, userAuthHeader, accessToken);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
}
- private void testListAuthorizedClientWithMultipleRefreshTokens (
- String userAuthHeader) throws KustvaktException {
+ private void testListAuthorizedClientWithMultipleRefreshTokens(String userAuthHeader) throws KustvaktException {
// client 2
- String code =
- requestAuthorizationCode(confidentialClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
-
+ String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
requestAuthorizedClientList(userAuthHeader);
}
- private void testListAuthorizedClientWithMultipleAccessTokens (
- String userAuthHeader) throws KustvaktException {
+ private void testListAuthorizedClientWithMultipleAccessTokens(String userAuthHeader) throws KustvaktException {
// client 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, "", code);
-
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
requestAuthorizedClientList(userAuthHeader);
}
- private void testListWithClientsFromAnotherUser (String userAuthHeader)
- throws KustvaktException {
-
- String aaaAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("aaa", "pwd");
-
+ private void testListWithClientsFromAnotherUser(String userAuthHeader) throws KustvaktException {
+ String aaaAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("aaa", "pwd");
// client 1
String code = requestAuthorizationCode(publicClientId, aaaAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, "", code);
-
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken1 = node.at("/access_token").asText();
-
// client 2
code = requestAuthorizationCode(confidentialClientId, aaaAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
-
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken2 = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
-
requestAuthorizedClientList(aaaAuthHeader);
requestAuthorizedClientList(userAuthHeader);
-
- testRevokeAllTokenViaSuperClient(publicClientId, aaaAuthHeader,
- accessToken1);
- testRevokeAllTokenViaSuperClient(confidentialClientId, aaaAuthHeader,
- accessToken2);
- testRequestTokenWithRevokedRefreshToken(confidentialClientId,
- clientSecret, refreshToken);
+ testRevokeAllTokenViaSuperClient(publicClientId, aaaAuthHeader, accessToken1);
+ testRevokeAllTokenViaSuperClient(confidentialClientId, aaaAuthHeader, accessToken2);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
}
-
- private void testRevokeAllTokenViaSuperClient (String clientId,
- String userAuthHeader, String accessToken)
- throws KustvaktException {
+
+ private void testRevokeAllTokenViaSuperClient(String clientId, String userAuthHeader, String accessToken) throws KustvaktException {
// check token before revoking
Response response = searchWithAccessToken(accessToken);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertTrue(node.at("/matches").size() > 0);
-
Form form = getSuperClientForm();
form.param("client_id", clientId);
-
- response = target().path(API_VERSION).path("oauth2").path("revoke")
- .path("super").path("all")
- .request()
- .header(Attributes.AUTHORIZATION, userAuthHeader)
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ response = target().path(API_VERSION).path("oauth2").path("revoke").path("super").path("all").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- assertEquals("SUCCESS", response.readEntity(String.class));
-
+ assertEquals(response.readEntity(String.class), "SUCCESS");
response = searchWithAccessToken(accessToken);
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
- assertEquals("Access token is invalid",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
index aca0a5c..32d33ae 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2ControllerTest.java
@@ -1,13 +1,12 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.time.ZonedDateTime;
import java.util.Set;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MultivaluedMap;
@@ -18,12 +17,10 @@
import org.apache.oltu.oauth2.common.error.OAuthError;
import org.apache.oltu.oauth2.common.message.types.GrantType;
import org.apache.oltu.oauth2.common.message.types.TokenType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.FullConfiguration;
@@ -35,620 +32,415 @@
/**
* @author margaretha
- *
*/
public class OAuth2ControllerTest extends OAuth2TestBase {
@Autowired
public FullConfiguration config;
-
+
public String userAuthHeader;
- public OAuth2ControllerTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "password");
+ public OAuth2ControllerTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "password");
}
@Test
- public void testAuthorizeConfidentialClient () throws KustvaktException {
+ public void testAuthorizeConfidentialClient() throws KustvaktException {
// with registered redirect URI
- Response response =
- requestAuthorizationCode("code", confidentialClientId, "",
- "match_info search client_info", state, userAuthHeader);
-
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", "match_info search client_info", state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- getQueryParamsFromURI(redirectUri);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(redirectUri);
assertNotNull(params.getFirst("code"));
assertEquals(state, params.getFirst("state"));
- assertEquals("match_info search client_info", params.getFirst("scope"));
+ assertEquals(params.getFirst("scope"), "match_info search client_info");
}
@Test
- public void testAuthorizePublicClient () throws KustvaktException {
+ public void testAuthorizePublicClient() throws KustvaktException {
// with registered redirect URI
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
assertNotNull(code);
}
@Test
- public void testAuthorizeWithRedirectUri () throws KustvaktException {
- Response response =
- requestAuthorizationCode("code", publicClientId2,
- "https://public.com/redirect", "search match_info",
- "", userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
+ public void testAuthorizeWithRedirectUri() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", publicClientId2, "https://public.com/redirect", "search match_info", "", userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
- assertEquals("https", redirectUri.getScheme());
- assertEquals("public.com", redirectUri.getHost());
- assertEquals("/redirect", redirectUri.getPath());
-
+ assertEquals(redirectUri.getScheme(), "https");
+ assertEquals(redirectUri.getHost(), "public.com");
+ assertEquals(redirectUri.getPath(), "/redirect");
String[] queryParts = redirectUri.getQuery().split("&");
assertTrue(queryParts[0].startsWith("code="));
- assertEquals("scope=match_info+search", queryParts[1]);
+ assertEquals(queryParts[1], "scope=match_info+search");
}
@Test
- public void testAuthorizeWithoutScope () throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- confidentialClientId, "", "", "", userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
+ public void testAuthorizeWithoutScope() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", "", "", userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
assertEquals(redirectUri.getScheme(), "https");
assertEquals(redirectUri.getHost(), "third.party.com");
assertEquals(redirectUri.getPath(), "/confidential/redirect");
-
String[] queryParts = redirectUri.getQuery().split("&");
assertTrue(queryParts[0].startsWith("error_description=scope+is+required"));
assertEquals(queryParts[1], "error=invalid_scope");
}
@Test
- public void testAuthorizeMissingClientId () throws KustvaktException {
- Response response = requestAuthorizationCode("code", "", "", "search",
- "", userAuthHeader);
+ public void testAuthorizeMissingClientId() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", "", "", "search", "", userAuthHeader);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("Missing parameters: client_id",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameters: client_id");
}
@Test
- public void testAuthorizeMissingRedirectUri () throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- publicClientId2, "", "search", state, userAuthHeader);
+ public void testAuthorizeMissingRedirectUri() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", publicClientId2, "", "search", state, userAuthHeader);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.CodeResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameter: redirect URI",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.CodeResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: redirect URI");
assertEquals(state, node.at("/state").asText());
}
@Test
public void testAuthorizeMissingResponseType() throws KustvaktException {
- Response response = requestAuthorizationCode("",
- confidentialClientId, "", "search", "", userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
- assertEquals("https://third.party.com/confidential/redirect?"
- + "error_description=Missing+parameters%3A+response_type&"
- + "error=invalid_request", response.getLocation().toString());
+ Response response = requestAuthorizationCode("", confidentialClientId, "", "search", "", userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals("https://third.party.com/confidential/redirect?" + "error_description=Missing+parameters%3A+response_type&" + "error=invalid_request", response.getLocation().toString());
}
-
+
@Test
- public void testAuthorizeMissingResponseTypeWithoutClientId () throws KustvaktException {
- Response response = requestAuthorizationCode("",
- "", "", "search", "", userAuthHeader);
-
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testAuthorizeMissingResponseTypeWithoutClientId() throws KustvaktException {
+ Response response = requestAuthorizationCode("", "", "", "search", "", userAuthHeader);
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(OAuthError.CodeResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameters: response_type client_id",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.CodeResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameters: response_type client_id");
}
@Test
- public void testAuthorizeInvalidClientId () throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- "unknown-client-id", "", "search", "", userAuthHeader);
+ public void testAuthorizeInvalidClientId() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", "unknown-client-id", "", "search", "", userAuthHeader);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_CLIENT, node.at("/error").asText());
- assertEquals("Unknown client: unknown-client-id",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Unknown client: unknown-client-id");
}
@Test
- public void testAuthorizeDifferentRedirectUri () throws KustvaktException {
+ public void testAuthorizeDifferentRedirectUri() throws KustvaktException {
String redirectUri = "https://different.uri/redirect";
- Response response = requestAuthorizationCode("code",
- confidentialClientId, redirectUri, "", state, userAuthHeader);
-
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
- response.getStatus());
+ Response response = requestAuthorizationCode("code", confidentialClientId, redirectUri, "", state, userAuthHeader);
+ testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), true, response.getStatus());
}
@Test
- public void testAuthorizeWithRedirectUriLocalhost ()
- throws KustvaktException {
- Response response = requestAuthorizationCode("code", publicClientId2,
- "http://localhost:1410", "search", state, userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
+ public void testAuthorizeWithRedirectUriLocalhost() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", publicClientId2, "http://localhost:1410", "search", state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
- MultivaluedMap<String, String> params =
- getQueryParamsFromURI(redirectUri);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(redirectUri);
assertNotNull(params.getFirst("code"));
assertEquals(state, params.getFirst("state"));
- assertEquals("search", params.getFirst("scope"));
+ assertEquals(params.getFirst("scope"), "search");
}
@Test
- public void testAuthorizeWithRedirectUriFragment ()
- throws KustvaktException {
- Response response = requestAuthorizationCode("code",
- publicClientId2, "http://public.com/index.html#redirect", "search",
- state, userAuthHeader);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
- response.getStatus());
+ public void testAuthorizeWithRedirectUriFragment() throws KustvaktException {
+ Response response = requestAuthorizationCode("code", publicClientId2, "http://public.com/index.html#redirect", "search", state, userAuthHeader);
+ testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), true, response.getStatus());
}
@Test
- public void testAuthorizeInvalidRedirectUri () throws KustvaktException {
+ public void testAuthorizeInvalidRedirectUri() throws KustvaktException {
// host not allowed by Apache URI Validator
String redirectUri = "https://public.uri/redirect";
- Response response = requestAuthorizationCode("code",
- publicClientId2, redirectUri, "", state, userAuthHeader);
- testInvalidRedirectUri(response.readEntity(String.class),
- response.getHeaderString("Content-Type"),true,
- response.getStatus());
+ Response response = requestAuthorizationCode("code", publicClientId2, redirectUri, "", state, userAuthHeader);
+ testInvalidRedirectUri(response.readEntity(String.class), response.getHeaderString("Content-Type"), true, response.getStatus());
}
@Test
- public void testAuthorizeInvalidResponseType () throws KustvaktException {
+ public void testAuthorizeInvalidResponseType() throws KustvaktException {
// without redirect URI in the request
- Response response = requestAuthorizationCode("string",
- confidentialClientId, "", "search", state, userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
- assertEquals("https://third.party.com/confidential/redirect?"
- + "error_description=Invalid+response_type+parameter+"
- + "value&state=thisIsMyState&" + "error=invalid_request",
- response.getLocation().toString());
-
+ Response response = requestAuthorizationCode("string", confidentialClientId, "", "search", state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals("https://third.party.com/confidential/redirect?" + "error_description=Invalid+response_type+parameter+" + "value&state=thisIsMyState&" + "error=invalid_request", response.getLocation().toString());
// with redirect URI, and no registered redirect URI
- response = requestAuthorizationCode("string", publicClientId2,
- "https://public.client.com/redirect", "", state,
- userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
- assertEquals("https://public.client.com/redirect?error_description="
- + "Invalid+response_type+parameter+value&state=thisIsMyState&"
- + "error=invalid_request", response.getLocation().toString());
-
+ response = requestAuthorizationCode("string", publicClientId2, "https://public.client.com/redirect", "", state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals("https://public.client.com/redirect?error_description=" + "Invalid+response_type+parameter+value&state=thisIsMyState&" + "error=invalid_request", response.getLocation().toString());
// with different redirect URI
String redirectUri = "https://different.uri/redirect";
- response = requestAuthorizationCode("string", confidentialClientId,
- redirectUri, "", state, userAuthHeader);
+ response = requestAuthorizationCode("string", confidentialClientId, redirectUri, "", state, userAuthHeader);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuthError.CodeResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Invalid redirect URI",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.CodeResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid redirect URI");
assertEquals(state, node.at("/state").asText());
-
// without redirect URI in the request and no registered
// redirect URI
- response = requestAuthorizationCode("string", publicClientId2, "", "",
- state, userAuthHeader);
+ response = requestAuthorizationCode("string", publicClientId2, "", "", state, userAuthHeader);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(OAuthError.CodeResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameter: redirect URI",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.CodeResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: redirect URI");
assertEquals(state, node.at("/state").asText());
}
@Test
- public void testAuthorizeInvalidScope () throws KustvaktException {
+ public void testAuthorizeInvalidScope() throws KustvaktException {
String scope = "read_address";
- Response response = requestAuthorizationCode("code",
- confidentialClientId, "", scope, state, userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
- assertEquals(
- "https://third.party.com/confidential/redirect?"
- + "error_description=read_address+is+an+invalid+scope&"
- + "state=thisIsMyState&error=invalid_scope",
- response.getLocation().toString());
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", scope, state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals("https://third.party.com/confidential/redirect?" + "error_description=read_address+is+an+invalid+scope&" + "state=thisIsMyState&error=invalid_scope", response.getLocation().toString());
}
@Test
- public void testAuthorizeUnsupportedTokenResponseType ()
- throws KustvaktException {
- Response response = requestAuthorizationCode("token",
- confidentialClientId, "", "search", state, userAuthHeader);
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
- assertEquals("https://third.party.com/confidential/redirect?"
- + "error_description=response_type+token+is+not+"
- + "supported&state=thisIsMyState&error=unsupported_"
- + "response_type", response.getLocation().toString());
+ public void testAuthorizeUnsupportedTokenResponseType() throws KustvaktException {
+ Response response = requestAuthorizationCode("token", confidentialClientId, "", "search", state, userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
+ assertEquals("https://third.party.com/confidential/redirect?" + "error_description=response_type+token+is+not+" + "supported&state=thisIsMyState&error=unsupported_" + "response_type", response.getLocation().toString());
}
@Test
- public void testRequestTokenAuthorizationPublic ()
- throws KustvaktException {
+ public void testRequestTokenAuthorizationPublic() throws KustvaktException {
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
-
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
String accessToken = node.at("/access_token").asText();
-
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertEquals(31536000, node.at("/expires_in").asInt());
-
testRevokeToken(accessToken, publicClientId, null, ACCESS_TOKEN_TYPE);
-
assertTrue(node.at("/refresh_token").isMissingNode());
}
@Test
- public void testRequestTokenAuthorizationConfidential ()
- throws KustvaktException {
-
+ public void testRequestTokenAuthorizationConfidential() throws KustvaktException {
String scope = "search";
- Response response = requestAuthorizationCode("code",
- confidentialClientId, "", scope, state, userAuthHeader);
- MultivaluedMap<String, String> params =
- getQueryParamsFromURI(response.getLocation());
+ Response response = requestAuthorizationCode("code", confidentialClientId, "", scope, state, userAuthHeader);
+ MultivaluedMap<String, String> params = getQueryParamsFromURI(response.getLocation());
String code = params.get("code").get(0);
String scopes = params.get("scope").get(0);
-
assertEquals(scopes, "search");
-
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
-
testRequestTokenWithUsedAuthorization(code);
-
String refreshToken = node.at("/refresh_token").asText();
-
testRefreshTokenExpiry(refreshToken);
testRequestRefreshTokenInvalidScope(confidentialClientId, refreshToken);
testRequestRefreshTokenInvalidClient(refreshToken);
testRequestRefreshTokenInvalidRefreshToken(confidentialClientId);
-
- testRequestRefreshToken(confidentialClientId, clientSecret,
- refreshToken);
+ testRequestRefreshToken(confidentialClientId, clientSecret, refreshToken);
}
- private void testRequestTokenWithUsedAuthorization (String code)
- throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ private void testRequestTokenWithUsedAuthorization(String code) throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
String entity = response.readEntity(String.class);
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_GRANT,
- node.at("/error").asText());
- assertEquals("Invalid authorization",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_GRANT, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid authorization");
}
@Test
- public void testRequestTokenInvalidAuthorizationCode ()
- throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, "blahblah");
+ public void testRequestTokenInvalidAuthorizationCode() throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, "blahblah");
String entity = response.readEntity(String.class);
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.at("/error").asText());
}
@Test
- public void testRequestTokenAuthorizationReplyAttack ()
- throws KustvaktException {
+ public void testRequestTokenAuthorizationReplyAttack() throws KustvaktException {
String redirect_uri = "https://third.party.com/confidential/redirect";
String scope = "search";
-
- Response response =
- requestAuthorizationCode("code", confidentialClientId,
- redirect_uri, scope, state, userAuthHeader);
+ Response response = requestAuthorizationCode("code", confidentialClientId, redirect_uri, scope, state, userAuthHeader);
String code = parseAuthorizationCode(response);
-
testRequestTokenAuthorizationInvalidClient(code);
testRequestTokenAuthorizationMissingRedirectUri(code);
testRequestTokenAuthorizationInvalidRedirectUri(code);
testRequestTokenAuthorizationRevoked(code, redirect_uri);
-
}
- private void testRequestTokenAuthorizationInvalidClient (String code)
- throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, "wrong_secret", code);
+ private void testRequestTokenAuthorizationInvalidClient(String code) throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, "wrong_secret", code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_CLIENT, node.at("/error").asText());
}
-
- private void testRequestTokenAuthorizationMissingRedirectUri (String code)
- throws KustvaktException {
- Response response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, "secret", code);
+
+ private void testRequestTokenAuthorizationMissingRedirectUri(String code) throws KustvaktException {
+ Response response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, "secret", code);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
- assertEquals("Missing redirect URI",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing redirect URI");
}
- private void testRequestTokenAuthorizationInvalidRedirectUri (String code)
- throws KustvaktException {
+ private void testRequestTokenAuthorizationInvalidRedirectUri(String code) throws KustvaktException {
Form tokenForm = new Form();
tokenForm.param("grant_type", "authorization_code");
tokenForm.param("client_id", confidentialClientId);
tokenForm.param("client_secret", "secret");
tokenForm.param("code", code);
tokenForm.param("redirect_uri", "https://blahblah.com");
-
Response response = requestToken(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
}
- private void testRequestTokenAuthorizationRevoked (String code, String uri)
- throws KustvaktException {
+ private void testRequestTokenAuthorizationRevoked(String code, String uri) throws KustvaktException {
Form tokenForm = new Form();
tokenForm.param("grant_type", "authorization_code");
tokenForm.param("client_id", confidentialClientId);
tokenForm.param("client_secret", "secret");
tokenForm.param("code", code);
tokenForm.param("redirect_uri", uri);
-
Response response = requestToken(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_GRANT,
- node.at("/error").asText());
- assertEquals("Invalid authorization",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_GRANT, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid authorization");
}
@Test
- public void testRequestTokenPasswordGrantConfidentialSuper ()
- throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(superClientId, clientSecret);
-
+ public void testRequestTokenPasswordGrantConfidentialSuper() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(superClientId, clientSecret);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertNotNull(node.at("/access_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
- assertEquals("all",node.at("/scope").asText());
-
-
+ assertEquals(node.at("/scope").asText(), "all");
String refresh = node.at("/refresh_token").asText();
- RefreshToken refreshToken =
- refreshTokenDao.retrieveRefreshToken(refresh);
+ RefreshToken refreshToken = refreshTokenDao.retrieveRefreshToken(refresh);
Set<AccessScope> scopes = refreshToken.getScopes();
assertEquals(1, scopes.size());
- assertEquals("[all]", scopes.toString());
-
+ assertEquals(scopes.toString(), "[all]");
testRefreshTokenExpiry(refresh);
}
-
+
@Test
- public void testRequestTokenPasswordGrantWithScope ()
- throws KustvaktException {
-
- String scope ="match_info search";
-
+ public void testRequestTokenPasswordGrantWithScope() throws KustvaktException {
+ String scope = "match_info search";
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", superClientId);
form.param("client_secret", clientSecret);
form.param("username", "dory");
form.param("password", "pwd");
- form.param("scope",scope);
-
+ form.param("scope", scope);
Response response = requestToken(form);
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertNotNull(node.at("/access_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
-
- assertEquals(scope,node.at("/scope").asText());
-
+ assertEquals(scope, node.at("/scope").asText());
String refreshToken = node.at("/refresh_token").asText();
- testRequestRefreshTokenWithUnauthorizedScope(superClientId, clientSecret,
- refreshToken,"all");
-
- testRequestRefreshTokenWithScope(superClientId, clientSecret,
- refreshToken,"search");
+ testRequestRefreshTokenWithUnauthorizedScope(superClientId, clientSecret, refreshToken, "all");
+ testRequestRefreshTokenWithScope(superClientId, clientSecret, refreshToken, "search");
}
@Test
- public void testRequestTokenPasswordGrantConfidentialNonSuper ()
- throws KustvaktException {
- Response response = requestTokenWithDoryPassword(
- confidentialClientId, clientSecret);
+ public void testRequestTokenPasswordGrantConfidentialNonSuper() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(confidentialClientId, clientSecret);
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT,
- node.at("/error").asText());
- assertEquals("Password grant is not allowed for third party clients",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Password grant is not allowed for third party clients");
}
@Test
- public void testRequestTokenPasswordGrantPublic ()
- throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(publicClientId, "");
+ public void testRequestTokenPasswordGrantPublic() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(publicClientId, "");
String entity = response.readEntity(String.class);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
- node.at("/error").asText());
- assertEquals("Password grant is not allowed for third party clients",
- node.at("/error_description").asText());
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Password grant is not allowed for third party clients");
}
@Test
- public void testRequestTokenPasswordGrantAuthorizationHeader ()
- throws KustvaktException {
+ public void testRequestTokenPasswordGrantAuthorizationHeader() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", superClientId);
form.param("username", "dory");
form.param("password", "password");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.AUTHORIZATION,
- "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.AUTHORIZATION, "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
/**
* In case, client_id is specified both in Authorization header
* and request body, client_id in the request body is ignored.
- *
+ *
* @throws KustvaktException
*/
@Test
- public void testRequestTokenPasswordGrantDifferentClientIds ()
- throws KustvaktException {
+ public void testRequestTokenPasswordGrantDifferentClientIds() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", "9aHsGW6QflV13ixNpez");
form.param("username", "dory");
form.param("password", "password");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.AUTHORIZATION,
- "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.AUTHORIZATION, "Basic ZkNCYlFrQXlZekk0TnpVeE1nOnNlY3JldA==").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
@Test
- public void testRequestTokenPasswordGrantMissingClientSecret ()
- throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(confidentialClientId, "");
+ public void testRequestTokenPasswordGrantMissingClientSecret() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(confidentialClientId, "");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameter: client_secret",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: client_secret");
}
@Test
- public void testRequestTokenPasswordGrantMissingClientId ()
- throws KustvaktException {
- Response response =
- requestTokenWithDoryPassword(null, clientSecret);
+ public void testRequestTokenPasswordGrantMissingClientId() throws KustvaktException {
+ Response response = requestTokenWithDoryPassword(null, clientSecret);
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameters: client_id",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameters: client_id");
}
@Test
- public void testRequestTokenClientCredentialsGrant ()
- throws KustvaktException {
-
+ public void testRequestTokenClientCredentialsGrant() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", confidentialClientId);
@@ -656,13 +448,11 @@
Response response = requestToken(form);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
// length?
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
}
@@ -671,395 +461,253 @@
* clients.
*/
@Test
- public void testRequestTokenClientCredentialsGrantPublic ()
- throws KustvaktException {
-
+ public void testRequestTokenClientCredentialsGrantPublic() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", publicClientId);
form.param("client_secret", "");
Response response = requestToken(form);
-
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.at("/error").asText());
- assertEquals("Missing parameters: client_secret",
- node.at("/error_description").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameters: client_secret");
}
@Test
- public void testRequestTokenClientCredentialsGrantReducedScope ()
- throws KustvaktException {
-
+ public void testRequestTokenClientCredentialsGrantReducedScope() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "client_credentials");
form.param("client_id", confidentialClientId);
form.param("client_secret", "secret");
form.param("scope", "preferred_username client_info");
-
Response response = requestToken(form);
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
// length?
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
- assertEquals("client_info", node.at("/scope").asText());
+ assertEquals(node.at("/scope").asText(), "client_info");
}
@Test
- public void testRequestTokenMissingGrantType () throws KustvaktException {
+ public void testRequestTokenMissingGrantType() throws KustvaktException {
Form form = new Form();
Response response = requestToken(form);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.at("/error").asText());
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.at("/error").asText());
}
@Test
- public void testRequestTokenUnsupportedGrant () throws KustvaktException {
-
+ public void testRequestTokenUnsupportedGrant() throws KustvaktException {
Form form = new Form();
form.param("grant_type", "blahblah");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("Invalid grant_type parameter value",
- node.get("error_description").asText());
- assertEquals(OAuthError.TokenResponse.INVALID_REQUEST,
- node.get("error").asText());
+ assertEquals(node.get("error_description").asText(), "Invalid grant_type parameter value");
+ assertEquals(OAuthError.TokenResponse.INVALID_REQUEST, node.get("error").asText());
}
- private void testRequestRefreshTokenInvalidScope (String clientId,
- String refreshToken) throws KustvaktException {
+ private void testRequestRefreshTokenInvalidScope(String clientId, String refreshToken) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
form.param("scope", "search serialize_query");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_SCOPE, node.at("/error").asText());
}
- private void testRequestRefreshToken (String clientId, String clientSecret,
- String refreshToken) throws KustvaktException {
+ private void testRequestRefreshToken(String clientId, String clientSecret, String refreshToken) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
-
String newRefreshToken = node.at("/refresh_token").asText();
assertNotNull(newRefreshToken);
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
-
assertTrue(!newRefreshToken.equals(refreshToken));
-
- testRequestTokenWithRevokedRefreshToken(clientId, clientSecret,
- refreshToken);
-
- testRevokeToken(newRefreshToken, clientId, clientSecret,
- REFRESH_TOKEN_TYPE);
- testRequestTokenWithRevokedRefreshToken(clientId, clientSecret,
- newRefreshToken);
+ testRequestTokenWithRevokedRefreshToken(clientId, clientSecret, refreshToken);
+ testRevokeToken(newRefreshToken, clientId, clientSecret, REFRESH_TOKEN_TYPE);
+ testRequestTokenWithRevokedRefreshToken(clientId, clientSecret, newRefreshToken);
}
-
- private void testRequestRefreshTokenWithUnauthorizedScope (String clientId,
- String clientSecret, String refreshToken, String scope)
- throws KustvaktException {
+ private void testRequestRefreshTokenWithUnauthorizedScope(String clientId, String clientSecret, String refreshToken, String scope) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
form.param("scope", scope);
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("token").request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_SCOPE, node.at("/error").asText());
}
-
- private void testRequestRefreshTokenWithScope (String clientId, String clientSecret,
- String refreshToken, String scope) throws KustvaktException {
+
+ private void testRequestRefreshTokenWithScope(String clientId, String clientSecret, String refreshToken, String scope) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", refreshToken);
- form.param("scope",scope);
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ form.param("scope", scope);
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
-
String newRefreshToken = node.at("/refresh_token").asText();
assertNotNull(newRefreshToken);
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
-
assertTrue(!newRefreshToken.equals(refreshToken));
-
- assertEquals(scope,node.at("/scope").asText());
+ assertEquals(scope, node.at("/scope").asText());
}
-
- private void testRequestRefreshTokenInvalidClient (String refreshToken)
- throws KustvaktException {
+
+ private void testRequestRefreshTokenInvalidClient(String refreshToken) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", "iBr3LsTCxOj7D2o0A5m");
form.param("refresh_token", refreshToken);
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_CLIENT, node.at("/error").asText());
}
- private void testRequestRefreshTokenInvalidRefreshToken (String clientId)
- throws KustvaktException {
+ private void testRequestRefreshTokenInvalidRefreshToken(String clientId) throws KustvaktException {
Form form = new Form();
form.param("grant_type", GrantType.REFRESH_TOKEN.toString());
form.param("client_id", clientId);
form.param("client_secret", clientSecret);
form.param("refresh_token", "Lia8s8w8tJeZSBlaQDrYV8ion3l");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_GRANT, node.at("/error").asText());
}
- private JsonNode requestTokenList (String userAuthHeader, String tokenType,
- String clientId) throws KustvaktException {
+ private JsonNode requestTokenList(String userAuthHeader, String tokenType, String clientId) throws KustvaktException {
Form form = new Form();
form.param("super_client_id", superClientId);
form.param("super_client_secret", clientSecret);
form.param("token_type", tokenType);
-
if (clientId != null && !clientId.isEmpty()) {
form.param("client_id", clientId);
}
-
- Response response = target().path(API_VERSION).path("oauth2")
- .path("token").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, userAuthHeader)
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").path("list").request().header(Attributes.AUTHORIZATION, userAuthHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private JsonNode requestTokenList (String userAuthHeader, String tokenType)
- throws KustvaktException {
+ private JsonNode requestTokenList(String userAuthHeader, String tokenType) throws KustvaktException {
return requestTokenList(userAuthHeader, tokenType, null);
}
@Test
- public void testListRefreshTokenConfidentialClient ()
- throws KustvaktException {
+ public void testListRefreshTokenConfidentialClient() throws KustvaktException {
String username = "gurgle";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, password);
-
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
// super client
- Response response = requestTokenWithPassword(superClientId,
- clientSecret, username, password);
+ Response response = requestTokenWithPassword(superClientId, clientSecret, username, password);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String refreshToken1 = node.at("/refresh_token").asText();
-
// client 1
- String code =
- requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ String code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// client 2
- code = requestAuthorizationCode(confidentialClientId2,
- clientRedirectUri, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId2, clientSecret, code, clientRedirectUri);
+ code = requestAuthorizationCode(confidentialClientId2, clientRedirectUri, userAuthHeader);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId2, clientSecret, code, clientRedirectUri);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// list
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(2, node.size());
assertEquals(confidentialClientId, node.at("/0/client_id").asText());
assertEquals(confidentialClientId2, node.at("/1/client_id").asText());
-
// client 1
code = requestAuthorizationCode(confidentialClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// another user
- String darlaAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("darla", "pwd");
-
+ String darlaAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("darla", "pwd");
// test listing clients
node = requestTokenList(darlaAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
-
// client 1
code = requestAuthorizationCode(confidentialClientId, darlaAuthHeader);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- response = requestTokenWithAuthorizationCodeAndForm(
- confidentialClientId, clientSecret, code);
-
+ response = requestTokenWithAuthorizationCodeAndForm(confidentialClientId, clientSecret, code);
node = JsonUtils.readTree(response.readEntity(String.class));
String refreshToken5 = node.at("/refresh_token").asText();
-
// list all refresh tokens
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(3, node.size());
-
// list refresh tokens from client 1
- node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE,
- confidentialClientId);
+ node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE, confidentialClientId);
assertEquals(2, node.size());
-
- testRevokeToken(refreshToken1, superClientId, clientSecret,
- REFRESH_TOKEN_TYPE);
- testRevokeToken(node.at("/0/token").asText(), confidentialClientId,
- clientSecret, REFRESH_TOKEN_TYPE);
- testRevokeToken(node.at("/1/token").asText(), confidentialClientId2,
- clientSecret, REFRESH_TOKEN_TYPE);
-
+ testRevokeToken(refreshToken1, superClientId, clientSecret, REFRESH_TOKEN_TYPE);
+ testRevokeToken(node.at("/0/token").asText(), confidentialClientId, clientSecret, REFRESH_TOKEN_TYPE);
+ testRevokeToken(node.at("/1/token").asText(), confidentialClientId2, clientSecret, REFRESH_TOKEN_TYPE);
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(1, node.size());
-
- testRevokeTokenViaSuperClient(node.at("/0/token").asText(),
- userAuthHeader);
+ testRevokeTokenViaSuperClient(node.at("/0/token").asText(), userAuthHeader);
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
-
// try revoking a token belonging to another user
// should not return any errors
testRevokeTokenViaSuperClient(refreshToken5, userAuthHeader);
node = requestTokenList(darlaAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(1, node.size());
-
testRevokeTokenViaSuperClient(refreshToken5, darlaAuthHeader);
node = requestTokenList(darlaAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
}
@Test
- public void testListTokenPublicClient () throws KustvaktException {
+ public void testListTokenPublicClient() throws KustvaktException {
String username = "nemo";
String password = "pwd";
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, password);
-
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, password);
// access token 1
String code = requestAuthorizationCode(publicClientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- publicClientId, "", code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken1 = node.at("/access_token").asText();
-
// access token 2
code = requestAuthorizationCode(publicClientId, userAuthHeader);
- response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "",
- code);
+ response = requestTokenWithAuthorizationCodeAndForm(publicClientId, "", code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken2 = node.at("/access_token").asText();
-
// list access tokens
node = requestTokenList(userAuthHeader, ACCESS_TOKEN_TYPE);
assertEquals(2, node.size());
-
// list refresh tokens
node = requestTokenList(userAuthHeader, REFRESH_TOKEN_TYPE);
assertEquals(0, node.size());
-
testRevokeTokenViaSuperClient(accessToken1, userAuthHeader);
node = requestTokenList(userAuthHeader, ACCESS_TOKEN_TYPE);
// System.out.println(node);
@@ -1069,22 +717,18 @@
assertNotNull(node.at("/0/created_date").asText());
assertNotNull(node.at("/0/expires_in").asLong());
assertNotNull(node.at("/0/user_authentication_time").asText());
-
assertEquals(publicClientId, node.at("/0/client_id").asText());
assertNotNull(node.at("/0/client_name").asText());
assertNotNull(node.at("/0/client_description").asText());
assertNotNull(node.at("/0/client_url").asText());
-
testRevokeTokenViaSuperClient(accessToken2, userAuthHeader);
node = requestTokenList(userAuthHeader, ACCESS_TOKEN_TYPE);
assertEquals(0, node.size());
}
-
- private void testRefreshTokenExpiry (String refreshToken)
- throws KustvaktException {
+
+ private void testRefreshTokenExpiry(String refreshToken) throws KustvaktException {
RefreshToken token = refreshTokenDao.retrieveRefreshToken(refreshToken);
- ZonedDateTime expiry = token.getCreatedDate()
- .plusSeconds(config.getRefreshTokenLongExpiry());
+ ZonedDateTime expiry = token.getCreatedDate().plusSeconds(config.getRefreshTokenLongExpiry());
assertTrue(expiry.equals(token.getExpiryDate()));
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2OpenIdControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2OpenIdControllerTest.java
index b53b90d..020ced2 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2OpenIdControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2OpenIdControllerTest.java
@@ -1,25 +1,23 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.net.URI;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.util.Date;
-
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import org.apache.http.entity.ContentType;
import org.apache.oltu.oauth2.common.message.types.TokenType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
import com.nimbusds.jose.JOSEException;
@@ -30,6 +28,7 @@
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;
import com.nimbusds.oauth2.sdk.GrantType;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.client.Entity;
@@ -47,155 +46,103 @@
@Autowired
private FullConfiguration config;
- private String redirectUri =
- "https://korap.ids-mannheim.de/confidential/redirect";
+ private String redirectUri = "https://korap.ids-mannheim.de/confidential/redirect";
+
private String username = "dory";
- private Response sendAuthorizationRequest (
- Form form) throws KustvaktException {
- return target().path(API_VERSION).path("oauth2").path("openid").path("authorize")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username,
- "password"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ private Response sendAuthorizationRequest(Form form) throws KustvaktException {
+ return target().path(API_VERSION).path("oauth2").path("openid").path("authorize").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
}
- private Response sendTokenRequest (
- Form form) throws KustvaktException {
- return target().path(API_VERSION).path("oauth2").path("openid").path("token")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ private Response sendTokenRequest(Form form) throws KustvaktException {
+ return target().path(API_VERSION).path("oauth2").path("openid").path("token").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
}
@Test
- public void testRequestAuthorizationCode ()
- throws ProcessingException,
- KustvaktException {
-
+ public void testRequestAuthorizationCode() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("response_type", "code");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
-
testRequestAuthorizationCodeWithoutOpenID(form, redirectUri);
form.param("scope", "openid");
-
testRequestAuthorizationCodeMissingRedirectUri(form);
testRequestAuthorizationCodeInvalidRedirectUri(form);
form.param("redirect_uri", redirectUri);
-
form.param("state", "thisIsMyState");
-
Response response = sendAuthorizationRequest(form);
URI location = response.getLocation();
- assertEquals(redirectUri, location.getScheme() + "://"
- + location.getHost() + location.getPath());
-
- MultiValueMap<String, String> params =
- UriComponentsBuilder.fromUri(location).build().getQueryParams();
+ assertEquals(redirectUri, location.getScheme() + "://" + location.getHost() + location.getPath());
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(location).build().getQueryParams();
assertNotNull(params.getFirst("code"));
- assertEquals("thisIsMyState", params.getFirst("state"));
+ assertEquals(params.getFirst("state"), "thisIsMyState");
}
- private void testRequestAuthorizationCodeWithoutOpenID (
- Form form, String redirectUri)
- throws KustvaktException {
+ private void testRequestAuthorizationCodeWithoutOpenID(Form form, String redirectUri) throws KustvaktException {
Response response = sendAuthorizationRequest(form);
URI location = response.getLocation();
// System.out.println(location.toString());
- assertEquals(redirectUri, location.getScheme() + "://"
- + location.getHost() + location.getPath());
+ assertEquals(redirectUri, location.getScheme() + "://" + location.getHost() + location.getPath());
}
- private void testRequestAuthorizationCodeMissingRedirectUri (
- Form form) throws KustvaktException {
+ private void testRequestAuthorizationCodeMissingRedirectUri(Form form) throws KustvaktException {
Response response = sendAuthorizationRequest(form);
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("redirect_uri is required",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "redirect_uri is required");
}
- private void testRequestAuthorizationCodeInvalidRedirectUri (
- Form form) throws KustvaktException {
+ private void testRequestAuthorizationCodeInvalidRedirectUri(Form form) throws KustvaktException {
form.param("redirect_uri", "blah");
Response response = sendAuthorizationRequest(form);
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid redirect URI",
- node.at("/error_description").asText());
-
+ assertEquals(node.at("/error_description").asText(), "Invalid redirect URI");
form.asMap().remove("redirect_uri");
}
@Test
- public void testRequestAuthorizationCodeMissingClientID ()
- throws KustvaktException {
+ public void testRequestAuthorizationCodeMissingClientID() throws KustvaktException {
Form form = new Form();
form.param("scope", "openid");
form.param("redirect_uri", redirectUri);
-
// error response is represented in JSON because redirect URI
// cannot be verified without client id
// Besides client_id is a mandatory parameter in a normal
// OAuth2 authorization request, thus it is checked first,
// before redirect_uri. see
// com.nimbusds.oauth2.sdk.AuthorizationRequest
-
Response response = sendAuthorizationRequest(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing client_id parameter",
- node.at("/error_description").asText());
-
+ assertEquals(node.at("/error_description").asText(), "Invalid request: Missing client_id parameter");
}
@Test
- public void testRequestAuthorizationCodeMissingResponseType ()
- throws KustvaktException {
+ public void testRequestAuthorizationCodeMissingResponseType() throws KustvaktException {
Form form = new Form();
form.param("scope", "openid");
form.param("redirect_uri", redirectUri);
form.param("client_id", "blah");
-
// client_id has not been verified yet
// MUST NOT automatically redirect the user-agent to the
// invalid redirection URI.
-
Response response = sendAuthorizationRequest(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing response_type parameter",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid request: Missing response_type parameter");
}
- private void testRequestAuthorizationCodeUnsupportedResponseType (
- Form form, String type)
- throws KustvaktException {
-
+ private void testRequestAuthorizationCodeUnsupportedResponseType(Form form, String type) throws KustvaktException {
Response response = sendAuthorizationRequest(form);
URI location = response.getLocation();
- assertEquals(MediaType.APPLICATION_FORM_URLENCODED,
- response.getMediaType().toString());
-
- MultiValueMap<String, String> params =
- UriComponentsBuilder.fromUri(location).build().getQueryParams();
- assertEquals("invalid_request", params.getFirst("error"));
- assertEquals("unsupported+response_type%3A+" + type,
- params.getFirst("error_description"));
+ assertEquals(MediaType.APPLICATION_FORM_URLENCODED, response.getMediaType().toString());
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(location).build().getQueryParams();
+ assertEquals(params.getFirst("error"), "invalid_request");
+ assertEquals("unsupported+response_type%3A+" + type, params.getFirst("error_description"));
}
/**
@@ -205,21 +152,18 @@
* <li>id_token</li>
* <li>id_token token</li>
* </ul>
- *
+ *
* @throws KustvaktException
*/
@Test
- public void testRequestAuthorizationCodeUnsupportedImplicitFlow ()
- throws KustvaktException {
+ public void testRequestAuthorizationCodeUnsupportedImplicitFlow() throws KustvaktException {
Form form = new Form();
form.param("scope", "openid");
form.param("redirect_uri", redirectUri);
form.param("response_type", "id_token");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
form.param("nonce", "nonce");
-
testRequestAuthorizationCodeUnsupportedResponseType(form, "id_token");
-
form.asMap().remove("response_type");
form.param("response_type", "id_token token");
testRequestAuthorizationCodeUnsupportedResponseType(form, "id_token");
@@ -233,14 +177,11 @@
* <li>code token</li>
* <li>code id_token token</li>
* </ul>
- *
- * @throws KustvaktExceptiony);
- * assertTrue(signedJWT.verify(verifier));
+ *
+ * @throws KustvaktExceptiony); assertTrue(signedJWT.verify(verifier));
*/
-
@Test
- public void testRequestAuthorizationCodeUnsupportedHybridFlow ()
- throws KustvaktException {
+ public void testRequestAuthorizationCodeUnsupportedHybridFlow() throws KustvaktException {
Form form = new Form();
form.param("scope", "openid");
form.param("redirect_uri", redirectUri);
@@ -248,16 +189,13 @@
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
form.param("nonce", "nonce");
testRequestAuthorizationCodeUnsupportedResponseType(form, "id_token");
-
form.asMap().remove("response_type");
form.param("response_type", "code token");
testRequestAuthorizationCodeUnsupportedResponseType(form, "token");
}
@Test
- public void testRequestAccessTokenWithAuthorizationCode ()
- throws KustvaktException, ParseException, InvalidKeySpecException,
- NoSuchAlgorithmException, JOSEException {
+ public void testRequestAccessTokenWithAuthorizationCode() throws KustvaktException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException, JOSEException {
String client_id = "fCBbQkAyYzI4NzUxMg";
String nonce = "thisIsMyNonce";
Form form = new Form();
@@ -267,14 +205,11 @@
form.param("scope", "openid");
form.param("state", "thisIsMyState");
form.param("nonce", nonce);
-
Response response = sendAuthorizationRequest(form);
URI location = response.getLocation();
- MultiValueMap<String, String> params =
- UriComponentsBuilder.fromUri(location).build().getQueryParams();
- assertEquals("thisIsMyState", params.getFirst("state"));
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(location).build().getQueryParams();
+ assertEquals(params.getFirst("state"), "thisIsMyState");
String code = params.getFirst("code");
-
Form tokenForm = new Form();
testRequestAccessTokenMissingGrant(tokenForm);
tokenForm.param("grant_type", "authorization_code");
@@ -284,62 +219,48 @@
testRequestAccessTokenMissingClientSecret(tokenForm);
tokenForm.param("client_secret", "secret");
tokenForm.param("redirect_uri", redirectUri);
-
Response tokenResponse = sendTokenRequest(tokenForm);
String entity = tokenResponse.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/access_token").asText());
assertNotNull(node.at("/refresh_token").asText());
- assertEquals(TokenType.BEARER.toString(),
- node.at("/token_type").asText());
+ assertEquals(TokenType.BEARER.toString(), node.at("/token_type").asText());
assertNotNull(node.at("/expires_in").asText());
String id_token = node.at("/id_token").asText();
assertNotNull(id_token);
-
verifyingIdToken(id_token, username, client_id, nonce);
}
- private void testRequestAccessTokenMissingGrant (
- Form tokenForm) throws KustvaktException {
+ private void testRequestAccessTokenMissingGrant(Form tokenForm) throws KustvaktException {
Response response = sendTokenRequest(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing grant_type parameter",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid request: Missing grant_type parameter");
}
- private void testRequestAccessTokenMissingClientId (
- Form tokenForm) throws KustvaktException {
+ private void testRequestAccessTokenMissingClientId(Form tokenForm) throws KustvaktException {
Response response = sendTokenRequest(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing required client_id "
- + "parameter", node.at("/error_description").asText());
+ assertEquals("Invalid request: Missing required client_id " + "parameter", node.at("/error_description").asText());
}
- private void testRequestAccessTokenMissingClientSecret (
- Form tokenForm) throws KustvaktException {
+ private void testRequestAccessTokenMissingClientSecret(Form tokenForm) throws KustvaktException {
Response response = sendTokenRequest(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Missing parameter: client_secret",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: client_secret");
}
- private void verifyingIdToken (String id_token, String username,
- String client_id, String nonce) throws ParseException,
- InvalidKeySpecException, NoSuchAlgorithmException, JOSEException {
+ private void verifyingIdToken(String id_token, String username, String client_id, String nonce) throws ParseException, InvalidKeySpecException, NoSuchAlgorithmException, JOSEException {
JWKSet keySet = config.getPublicKeySet();
RSAKey publicKey = (RSAKey) keySet.getKeyByKeyId(config.getRsaKeyId());
-
SignedJWT signedJWT = SignedJWT.parse(id_token);
JWSVerifier verifier = new RSASSAVerifier(publicKey);
assertTrue(signedJWT.verify(verifier));
-
JWTClaimsSet claimsSet = signedJWT.getJWTClaimsSet();
assertEquals(client_id, claimsSet.getAudience().get(0));
assertEquals(username, claimsSet.getSubject());
@@ -351,75 +272,56 @@
// no openid
@Test
- public void testRequestAccessTokenWithPassword ()
- throws KustvaktException, ParseException, InvalidKeySpecException,
- NoSuchAlgorithmException, JOSEException {
+ public void testRequestAccessTokenWithPassword() throws KustvaktException, ParseException, InvalidKeySpecException, NoSuchAlgorithmException, JOSEException {
// public client
String client_id = "8bIDtZnH6NvRkW2Fq";
Form tokenForm = new Form();
testRequestAccessTokenMissingGrant(tokenForm);
-
tokenForm.param("grant_type", GrantType.PASSWORD.toString());
testRequestAccessTokenMissingUsername(tokenForm);
-
tokenForm.param("username", username);
testRequestAccessTokenMissingPassword(tokenForm);
-
tokenForm.param("password", "pass");
tokenForm.param("client_id", client_id);
-
Response tokenResponse = sendTokenRequest(tokenForm);
String entity = tokenResponse.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
- node.at("/error").asText());
- assertEquals("Password grant is not allowed for third party clients",
- node.at("/error_description").asText());
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Password grant is not allowed for third party clients");
}
- private void testRequestAccessTokenMissingUsername (
- Form tokenForm) throws KustvaktException {
+ private void testRequestAccessTokenMissingUsername(Form tokenForm) throws KustvaktException {
Response response = sendTokenRequest(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing or empty username parameter",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid request: Missing or empty username parameter");
}
- private void testRequestAccessTokenMissingPassword (
- Form tokenForm) throws KustvaktException {
+ private void testRequestAccessTokenMissingPassword(Form tokenForm) throws KustvaktException {
Response response = sendTokenRequest(tokenForm);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
- assertEquals("Invalid request: Missing or empty password parameter",
- node.at("/error_description").asText());
+ assertEquals(node.at("/error_description").asText(), "Invalid request: Missing or empty password parameter");
}
@Test
- public void testPublicKeyAPI () throws KustvaktException {
- Response response = target().path(API_VERSION).path("oauth2").path("openid")
- .path("jwks")
- .request()
- .get();
+ public void testPublicKeyAPI() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2").path("openid").path("jwks").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(1, node.at("/keys").size());
node = node.at("/keys/0");
- assertEquals("RSA", node.at("/kty").asText());
+ assertEquals(node.at("/kty").asText(), "RSA");
assertEquals(config.getRsaKeyId(), node.at("/kid").asText());
assertNotNull(node.at("/e").asText());
assertNotNull(node.at("/n").asText());
}
@Test
- public void testOpenIDConfiguration () throws KustvaktException {
- Response response = target().path(API_VERSION).path("oauth2").path("openid")
- .path("config")
- .request()
- .get();
+ public void testOpenIDConfiguration() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("oauth2").path("openid").path("config").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node.at("/issuer"));
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
index bcce74f..18ffdc9 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2PluginTest.java
@@ -1,10 +1,10 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
import java.io.IOException;
import java.util.ArrayList;
@@ -23,12 +23,10 @@
import javax.ws.rs.core.Response.Status;
import org.apache.http.entity.ContentType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.entity.InstalledPlugin;
@@ -44,16 +42,14 @@
public class OAuth2PluginTest extends OAuth2TestBase {
private String username = "plugin-user";
+
@Autowired
private InstalledPluginDao pluginDao;
@Test
- public void testRegisterPlugin () throws
- ProcessingException, KustvaktException {
+ public void testRegisterPlugin() throws ProcessingException, KustvaktException {
JsonNode source = JsonUtils.readTree("{ \"plugin\" : \"source\"}");
-
int refreshTokenExpiry = TimeUtils.convertTimeToSeconds("90D");
-
String clientName = "Plugin";
OAuth2ClientJson json = new OAuth2ClientJson();
json.setName(clientName);
@@ -61,7 +57,6 @@
json.setDescription("This is a plugin test client.");
json.setSource(source);
json.setRefreshTokenExpiry(refreshTokenExpiry);
-
Response response = registerClient(username, json);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
@@ -69,22 +64,19 @@
String clientSecret = node.at("/client_secret").asText();
assertNotNull(clientId);
assertNotNull(clientSecret);
-
testInstallPluginNotPermitted(clientId);
testRetrievePluginInfo(clientId, refreshTokenExpiry);
-
node = listPlugins(false);
assertEquals(3, node.size());
- node = listPlugins(true); // permitted only
+ // permitted only
+ node = listPlugins(true);
assertEquals(2, node.size());
-
- testListUserRegisteredPlugins(username, clientId, clientName,
- refreshTokenExpiry);
+ testListUserRegisteredPlugins(username, clientId, clientName, refreshTokenExpiry);
deregisterClient(username, clientId);
}
@Test
- public void testRegisterPublicPlugin () throws KustvaktException {
+ public void testRegisterPublicPlugin() throws KustvaktException {
JsonNode source = JsonUtils.readTree("{ \"plugin\" : \"source\"}");
String clientName = "Public Plugin";
OAuth2ClientJson json = new OAuth2ClientJson();
@@ -92,70 +84,52 @@
json.setType(OAuth2ClientType.PUBLIC);
json.setDescription("This is a public plugin.");
json.setSource(source);
-
Response response = registerClient(username, json);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertFalse(node.at("/error_description").isMissingNode());
-
-// assertEquals(Status.OK.getStatusCode(), response.getStatus());
-// String clientId = node.at("/client_id").asText();
-// assertTrue(node.at("/client_secret").isMissingNode());
-//
-// deregisterClient(username, clientId);
+ // assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ // String clientId = node.at("/client_id").asText();
+ // assertTrue(node.at("/client_secret").isMissingNode());
+ //
+ // deregisterClient(username, clientId);
}
- private void testRetrievePluginInfo (String clientId,
- int refreshTokenExpiry) throws
- ProcessingException, KustvaktException {
+ private void testRetrievePluginInfo(String clientId, int refreshTokenExpiry) throws ProcessingException, KustvaktException {
JsonNode clientInfo = retrieveClientInfo(clientId, username);
assertEquals(clientId, clientInfo.at("/client_id").asText());
- assertEquals("Plugin", clientInfo.at("/client_name").asText());
-
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
- clientInfo.at("/client_type").asText());
+ assertEquals(clientInfo.at("/client_name").asText(), "Plugin");
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), clientInfo.at("/client_type").asText());
assertNotNull(clientInfo.at("/client_description").asText());
assertNotNull(clientInfo.at("/source").asText());
assertFalse(clientInfo.at("/permitted").asBoolean());
assertEquals(username, clientInfo.at("/registered_by").asText());
assertNotNull(clientInfo.at("/registration_date"));
- assertEquals(refreshTokenExpiry,
- clientInfo.at("/refresh_token_expiry").asInt());
+ assertEquals(refreshTokenExpiry, clientInfo.at("/refresh_token_expiry").asInt());
}
- private void testListUserRegisteredPlugins (String username,
- String clientId, String clientName, int refreshTokenExpiry)
- throws ProcessingException,
- KustvaktException {
-
+ private void testListUserRegisteredPlugins(String username, String clientId, String clientName, int refreshTokenExpiry) throws ProcessingException, KustvaktException {
JsonNode node = listUserRegisteredClients(username);
assertEquals(1, node.size());
assertEquals(clientId, node.at("/0/client_id").asText());
assertEquals(clientName, node.at("/0/client_name").asText());
- assertEquals(OAuth2ClientType.CONFIDENTIAL.name(),
- node.at("/0/client_type").asText());
+ assertEquals(OAuth2ClientType.CONFIDENTIAL.name(), node.at("/0/client_type").asText());
assertFalse(node.at("/0/permitted").asBoolean());
assertFalse(node.at("/0/registration_date").isMissingNode());
assertFalse(node.at("/0/source").isMissingNode());
- assertEquals(refreshTokenExpiry,
- node.at("/0/refresh_token_expiry").asInt());
+ assertEquals(refreshTokenExpiry, node.at("/0/refresh_token_expiry").asInt());
}
@Test
- public void testListPluginsUnauthorizedPublic ()
- throws ProcessingException,
- KustvaktException {
+ public void testListPluginsUnauthorizedPublic() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", publicClientId);
testListPluginsClientUnauthorized(form);
}
@Test
- public void testListPluginsUnauthorizedConfidential ()
- throws ProcessingException,
- KustvaktException {
+ public void testListPluginsUnauthorizedConfidential() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId2);
form.param("super_client_secret", clientSecret);
@@ -163,137 +137,83 @@
}
@Test
- public void testListPluginsMissingClientSecret ()
- throws ProcessingException,
- KustvaktException {
+ public void testListPluginsMissingClientSecret() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId);
-
- Response response = target().path(API_VERSION).path("plugins")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
assertEquals(OAuth2Error.INVALID_REQUEST, node.at("/error").asText());
assertFalse(node.at("/error_description").isMissingNode());
}
- private void testListPluginsClientUnauthorized (
- Form form)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("plugins")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ private void testListPluginsClientUnauthorized(Form form) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
- assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT,
- node.at("/error").asText());
+ assertEquals(OAuth2Error.UNAUTHORIZED_CLIENT, node.at("/error").asText());
assertFalse(node.at("/error_description").isMissingNode());
}
@Test
- public void testListPluginsUserUnauthorized ()
- throws ProcessingException,
- KustvaktException {
-
+ public void testListPluginsUserUnauthorized() throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
- Response response = target().path(API_VERSION).path("plugins")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer blahblah")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, "Bearer blahblah").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
}
-
-
@Test
- public void testListPluginsConcurrent () throws InterruptedException {
+ public void testListPluginsConcurrent() throws InterruptedException {
ExecutorService executorService = Executors.newFixedThreadPool(3);
List<Future<Void>> futures = new ArrayList<>();
-
for (int i = 0; i < 3; i++) {
- futures.add(executorService
- .submit(new PluginListCallable("Thread " + (i + 1))));
+ futures.add(executorService.submit(new PluginListCallable("Thread " + (i + 1))));
}
-
executorService.shutdown();
executorService.awaitTermination(2, TimeUnit.SECONDS);
-
for (Future<Void> future : futures) {
try {
- future.get(); // This will re-throw any exceptions
- // that occurred in threads
- }
- catch (ExecutionException e) {
+ // This will re-throw any exceptions
+ future.get();
+ // that occurred in threads
+ } catch (ExecutionException e) {
fail("Test failed: " + e.getCause().getMessage());
}
}
}
class PluginListCallable implements Callable<Void> {
+
private final String name;
- public PluginListCallable (String name) {
+ public PluginListCallable(String name) {
this.name = name;
}
@Override
- public Void call () {
+ public Void call() {
Form form = getSuperClientForm();
try {
- Response response = target().path(API_VERSION).path("plugins")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(
- username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
- }
- catch (KustvaktException e) {
+ } catch (KustvaktException e) {
e.printStackTrace();
throw new RuntimeException(name, e);
}
return null;
}
}
-
-
+
@Test
- public void testListAllPlugins () throws
- ProcessingException, KustvaktException {
+ public void testListAllPlugins() throws ProcessingException, KustvaktException {
JsonNode node = listPlugins(false);
assertEquals(2, node.size());
assertFalse(node.at("/0/client_id").isMissingNode());
@@ -304,318 +224,205 @@
assertFalse(node.at("/0/registration_date").isMissingNode());
assertFalse(node.at("/0/source").isMissingNode());
assertFalse(node.at("/0/refresh_token_expiry").isMissingNode());
-
// assertTrue(node.at("/1/refresh_token_expiry").isMissingNode());
}
- private JsonNode listPlugins (boolean permitted_only)
- throws ProcessingException,
- KustvaktException {
-
+ private JsonNode listPlugins(boolean permitted_only) throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
if (permitted_only) {
form.param("permitted_only", Boolean.toString(permitted_only));
}
- Response response = target().path(API_VERSION).path("plugins")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("plugins").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private void testInstallConfidentialPlugin (String superClientId,
- String clientId, String username) throws
- ProcessingException, KustvaktException {
+ private void testInstallConfidentialPlugin(String superClientId, String clientId, String username) throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
Response response = installPlugin(form);
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(clientId, node.at("/client_id").asText());
assertEquals(superClientId, node.at("/super_client_id").asText());
-
assertFalse(node.at("/name").isMissingNode());
assertFalse(node.at("/description").isMissingNode());
assertFalse(node.at("/url").isMissingNode());
assertFalse(node.at("/installed_date").isMissingNode());
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testRetrieveInstalledPlugin(superClientId, clientId, username);
}
@Test
- public void testInstallPublicPlugin () throws
- ProcessingException, KustvaktException {
+ public void testInstallPublicPlugin() throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", publicClientId2);
Response response = installPlugin(form);
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(publicClientId2, node.at("/client_id").asText());
assertEquals(superClientId, node.at("/super_client_id").asText());
-
assertFalse(node.at("/name").isMissingNode());
assertFalse(node.at("/description").isMissingNode());
assertFalse(node.at("/url").isMissingNode());
assertFalse(node.at("/installed_date").isMissingNode());
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testInstallPluginRedundant(form);
-
testRetrieveInstalledPlugin(superClientId, publicClientId2, username);
-
response = uninstallPlugin(publicClientId2, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertTrue(node.isEmpty());
}
- private void testInstallPluginRedundant (
- Form form)
- throws ProcessingException,
- KustvaktException {
+ private void testInstallPluginRedundant(Form form) throws ProcessingException, KustvaktException {
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.PLUGIN_HAS_BEEN_INSTALLED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.PLUGIN_HAS_BEEN_INSTALLED, node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
- private void testInstallPluginNotPermitted (String clientId)
- throws ProcessingException,
- KustvaktException {
+ private void testInstallPluginNotPermitted(String clientId) throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.PLUGIN_NOT_PERMITTED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.PLUGIN_NOT_PERMITTED, node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingClientId ()
- throws ProcessingException,
- KustvaktException {
+ public void testInstallPluginMissingClientId() throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginInvalidClientId ()
- throws ProcessingException,
- KustvaktException {
+ public void testInstallPluginInvalidClientId() throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", "unknown");
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("Unknown client: unknown",
- node.at("/error_description").asText());
- assertEquals("invalid_client", node.at("/error").asText());
+ assertEquals(node.at("/error_description").asText(), "Unknown client: unknown");
+ assertEquals(node.at("/error").asText(), "invalid_client");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingSuperClientSecret ()
- throws ProcessingException,
- KustvaktException {
+ public void testInstallPluginMissingSuperClientSecret() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", superClientId);
-
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("Missing parameter: super_client_secret",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
-
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: super_client_secret");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginMissingSuperClientId ()
- throws ProcessingException,
- KustvaktException {
+ public void testInstallPluginMissingSuperClientId() throws ProcessingException, KustvaktException {
Form form = new Form();
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("Missing parameter: super_client_id",
- node.at("/error_description").asText());
- assertEquals("invalid_request", node.at("/error").asText());
-
+ assertEquals(node.at("/error_description").asText(), "Missing parameter: super_client_id");
+ assertEquals(node.at("/error").asText(), "invalid_request");
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testInstallPluginUnauthorizedClient ()
- throws ProcessingException,
- KustvaktException {
+ public void testInstallPluginUnauthorizedClient() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("super_client_id", confidentialClientId);
form.param("super_client_secret", clientSecret);
-
Response response = installPlugin(form);
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("unauthorized_client", node.at("/error").asText());
-
+ assertEquals(node.at("/error").asText(), "unauthorized_client");
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
}
- private Response installPlugin (Form form)
- throws ProcessingException,
- KustvaktException {
- return target().path(API_VERSION).path("plugins").path("install")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ private Response installPlugin(Form form) throws ProcessingException, KustvaktException {
+ return target().path(API_VERSION).path("plugins").path("install").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
}
- private Response uninstallPlugin (String clientId, String username)
- throws ProcessingException,
- KustvaktException {
-
+ private Response uninstallPlugin(String clientId, String username) throws ProcessingException, KustvaktException {
Form form = getSuperClientForm();
form.param("client_id", clientId);
-
- return target().path(API_VERSION).path("plugins").path("uninstall")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
+ return target().path(API_VERSION).path("plugins").path("uninstall").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
}
- private void testRetrieveInstalledPlugin (String superClientId,
- String clientId, String installedBy) throws KustvaktException {
- InstalledPlugin plugin = pluginDao
- .retrieveInstalledPlugin(superClientId, clientId, installedBy);
+ private void testRetrieveInstalledPlugin(String superClientId, String clientId, String installedBy) throws KustvaktException {
+ InstalledPlugin plugin = pluginDao.retrieveInstalledPlugin(superClientId, clientId, installedBy);
assertEquals(clientId, plugin.getClient().getId());
assertEquals(superClientId, plugin.getSuperClient().getId());
assertEquals(installedBy, plugin.getInstalledBy());
-
assertTrue(plugin.getId() > 0);
assertTrue(plugin.getInstalledDate() != null);
}
@Test
- public void testListUserInstalledPlugins ()
- throws ProcessingException,
- KustvaktException, IOException {
-
- testInstallConfidentialPlugin(superClientId, confidentialClientId,
- username);
-
+ public void testListUserInstalledPlugins() throws ProcessingException, KustvaktException, IOException {
+ testInstallConfidentialPlugin(superClientId, confidentialClientId, username);
JsonNode node = testRequestAccessToken(confidentialClientId);
- String accessToken = node.at("/access_token").asText();
+ String accessToken = node.at("/access_token").asText();
String refreshToken = node.at("/refresh_token").asText();
testSearchWithOAuth2Token(accessToken);
-
- testInstallConfidentialPlugin(superClientId, confidentialClientId2,
- username);
-
+ testInstallConfidentialPlugin(superClientId, confidentialClientId2, username);
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(2, node.size());
-
- Response response =
- uninstallPlugin(confidentialClientId, username);
+ Response response = uninstallPlugin(confidentialClientId, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(1, node.size());
-
- testRequestTokenWithRevokedRefreshToken(confidentialClientId,
- clientSecret, refreshToken);
+ testRequestTokenWithRevokedRefreshToken(confidentialClientId, clientSecret, refreshToken);
testSearchWithRevokedAccessToken(accessToken);
-
response = uninstallPlugin(confidentialClientId2, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(0, node.size());
-
testReinstallUninstalledPlugin();
-
testUninstallNotInstalledPlugin();
}
-
- private void testReinstallUninstalledPlugin ()
- throws ProcessingException, KustvaktException {
- testInstallConfidentialPlugin(superClientId, confidentialClientId2,
- username);
+
+ private void testReinstallUninstalledPlugin() throws ProcessingException, KustvaktException {
+ testInstallConfidentialPlugin(superClientId, confidentialClientId2, username);
JsonNode node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(1, node.size());
-
Response response = uninstallPlugin(confidentialClientId2, username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
node = retrieveUserInstalledPlugin(getSuperClientForm());
assertEquals(0, node.size());
}
- private JsonNode testRequestAccessToken (String clientId) throws KustvaktException {
- String userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "password");
+ private JsonNode testRequestAccessToken(String clientId) throws KustvaktException {
+ String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
String code = requestAuthorizationCode(clientId, userAuthHeader);
- Response response = requestTokenWithAuthorizationCodeAndForm(
- clientId, clientSecret, code);
+ Response response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
return node;
}
- private void testUninstallNotInstalledPlugin ()
- throws ProcessingException,
- KustvaktException {
- Response response =
- uninstallPlugin(confidentialClientId2, username);
+ private void testUninstallNotInstalledPlugin() throws ProcessingException, KustvaktException {
+ Response response = uninstallPlugin(confidentialClientId2, username);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
-
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
}
- private JsonNode retrieveUserInstalledPlugin (
- Form form)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("plugins")
- .path("installed")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ private JsonNode retrieveUserInstalledPlugin(Form form) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("plugins").path("installed").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
-
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
index 61aa2f4..0810483 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2RClientTest.java
@@ -1,21 +1,18 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.io.IOException;
import java.net.URI;
-
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.oauth2.constant.OAuth2ClientType;
@@ -25,14 +22,14 @@
public class OAuth2RClientTest extends OAuth2TestBase {
private String username = "OAuth2ClientControllerTest";
+
private String userAuthHeader;
- public OAuth2RClientTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("R-user", "password");
+ public OAuth2RClientTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("R-user", "password");
}
- public OAuth2ClientJson createOAuth2RClient () {
+ public OAuth2ClientJson createOAuth2RClient() {
OAuth2ClientJson client = new OAuth2ClientJson();
client.setName("R client");
client.setType(OAuth2ClientType.PUBLIC);
@@ -42,60 +39,39 @@
}
@Test
- public void testRClientWithLocalhost ()
- throws ProcessingException, KustvaktException, IOException {
+ public void testRClientWithLocalhost() throws ProcessingException, KustvaktException, IOException {
// Register client
OAuth2ClientJson clientJson = createOAuth2RClient();
Response response = registerClient(username, clientJson);
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String clientId = node.at("/client_id").asText();
-
// send authorization
String code = testAuthorize(clientId);
-
// send token request
- response =
- requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
-
// testing
String accessToken = node.at("/access_token").asText();
testSearchWithOAuth2Token(accessToken);
-
// cleaning up
deregisterClient(username, clientId);
-
testSearchWithRevokedAccessToken(accessToken);
}
- private String testAuthorize (String clientId) throws KustvaktException {
-
- Response response = requestAuthorizationCode("code", clientId, "",
- "search", "", userAuthHeader);
-
- assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(),
- response.getStatus());
-
+ private String testAuthorize(String clientId) throws KustvaktException {
+ Response response = requestAuthorizationCode("code", clientId, "", "search", "", userAuthHeader);
+ assertEquals(Status.TEMPORARY_REDIRECT.getStatusCode(), response.getStatus());
URI redirectUri = response.getLocation();
-
- assertEquals("http", redirectUri.getScheme());
- assertEquals("localhost", redirectUri.getHost());
+ assertEquals(redirectUri.getScheme(), "http");
+ assertEquals(redirectUri.getHost(), "localhost");
assertEquals(1410, redirectUri.getPort());
-
- MultiValueMap<String, String> params = UriComponentsBuilder
- .fromUri(redirectUri).build().getQueryParams();
+ MultiValueMap<String, String> params = UriComponentsBuilder.fromUri(redirectUri).build().getQueryParams();
String code = params.getFirst("code");
assertNotNull(code);
- assertEquals("search", params.getFirst("scope"));
+ assertEquals(params.getFirst("scope"), "search");
return code;
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
index 351491b..307af6c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/OAuth2TestBase.java
@@ -1,9 +1,5 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-
import java.io.IOException;
import java.net.URI;
import java.time.ZoneId;
@@ -53,6 +49,8 @@
import de.ids_mannheim.korap.utils.TimeUtils;
import de.ids_mannheim.korap.web.input.OAuth2ClientJson;
+import static org.junit.jupiter.api.Assertions.*;
+
/**
* Provides common methods and variables for OAuth2 tests,
* and does not run any test.
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
index 2e5ef40..f440cc3 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceControllerTest.java
@@ -1,12 +1,12 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import org.apache.http.entity.ContentType;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -24,381 +24,196 @@
public class QueryReferenceControllerTest extends SpringJerseyTest {
private String testUser = "qRefControllerTest";
+
private String adminUser = "admin";
+
private String system = "system";
- private void testRetrieveQueryByName (String qName, String query,
- String queryCreator, String username, ResourceType resourceType,
- CorpusAccess access) throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("query")
- .path("~" + queryCreator).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .get();
+ private void testRetrieveQueryByName(String qName, String query, String queryCreator, String username, ResourceType resourceType, CorpusAccess access) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").path("~" + queryCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(qName, node.at("/name").asText());
assertEquals(resourceType.displayName(), node.at("/type").asText());
assertEquals(queryCreator, node.at("/createdBy").asText());
assertEquals(query, node.at("/query").asText());
- assertEquals("poliqarp", node.at("/queryLanguage").asText());
+ assertEquals(node.at("/queryLanguage").asText(), "poliqarp");
assertEquals(access.name(), node.at("/requiredAccess").asText());
}
-
- private void testUpdateQuery (String qName, String qCreator,
- String username, ResourceType type)
- throws ProcessingException,
- KustvaktException {
- String json = "{\"query\": \"Sonne\""
- + ",\"queryLanguage\": \"poliqarp\"}";
-
- Response response = target().path(API_VERSION).path("query")
- .path("~"+qCreator).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+
+ private void testUpdateQuery(String qName, String qCreator, String username, ResourceType type) throws ProcessingException, KustvaktException {
+ String json = "{\"query\": \"Sonne\"" + ",\"queryLanguage\": \"poliqarp\"}";
+ Response response = target().path(API_VERSION).path("query").path("~" + qCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
-
testRetrieveQueryByName(qName, "Sonne", qCreator, username, type, CorpusAccess.PUB);
}
-
+
@Test
- public void testCreatePrivateQuery () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"der\"}";
-
+ public void testCreatePrivateQuery() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"der\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
- testRetrieveQueryByName(qName, "der", testUser, testUser, ResourceType.PRIVATE,
- CorpusAccess.PUB);
-
- testUpdateQuery(qName, testUser, testUser,ResourceType.PRIVATE);
+ testRetrieveQueryByName(qName, "der", testUser, testUser, ResourceType.PRIVATE, CorpusAccess.PUB);
+ testUpdateQuery(qName, testUser, testUser, ResourceType.PRIVATE);
testDeleteQueryByName(qName, testUser, testUser);
}
@Test
- public void testCreatePublishQuery () throws KustvaktException {
- String json = "{\"type\": \"PUBLISHED\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"Regen\"}";
-
+ public void testCreatePublishQuery() throws KustvaktException {
+ String json = "{\"type\": \"PUBLISHED\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Regen\"}";
String qName = "publish_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
- testRetrieveQueryByName(qName, "Regen", testUser, testUser, ResourceType.PUBLISHED,
- CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Regen", testUser, testUser, ResourceType.PUBLISHED, CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
// check if hidden group has been created
-
}
-
+
@Test
- public void testCreateUserQueryByAdmin () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"Sommer\"}";
-
+ public void testCreateUserQueryByAdmin() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
String qName = "marlin-query";
- Response response = target().path(API_VERSION).path("query")
- .path("~marlin").path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(adminUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~marlin").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(adminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
testRetrieveQueryByName(qName, "Sommer", "marlin", adminUser, ResourceType.PRIVATE, CorpusAccess.PUB);
-
testUpdateQuery(qName, "marlin", adminUser, ResourceType.PRIVATE);
testDeleteQueryByName(qName, "marlin", adminUser);
}
-
+
@Test
- public void testCreateSystemQuery () throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"Sommer\"}";
-
+ public void testCreateSystemQuery() throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
String qName = "system-query";
- Response response = target().path(API_VERSION).path("query")
- .path("~system").path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(adminUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~system").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(adminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
testRetrieveQueryByName(qName, "Sommer", system, adminUser, ResourceType.SYSTEM, CorpusAccess.PUB);
testUpdateQuery(qName, system, adminUser, ResourceType.SYSTEM);
testDeleteSystemQueryUnauthorized(qName);
testDeleteQueryByName(qName, system, adminUser);
}
-
+
@Test
- public void testCreateSystemQueryUnauthorized () throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"Sommer\"}";
-
- Response response = target().path(API_VERSION).path("query")
- .path("~"+testUser).path("system-query")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ public void testCreateSystemQueryUnauthorized() throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sommer\"}";
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path("system-query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser,
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
}
-
+
@Test
- public void testCreateQueryMissingQueryType () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryLanguage\": \"poliqarp\""
- + ",\"query\": \"Sohn\"}";
-
+ public void testCreateQueryMissingQueryType() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryLanguage\": \"poliqarp\"" + ",\"query\": \"Sohn\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
- testRetrieveQueryByName(qName, "Sohn", testUser, testUser, ResourceType.PRIVATE,
- CorpusAccess.PUB);
+ testRetrieveQueryByName(qName, "Sohn", testUser, testUser, ResourceType.PRIVATE, CorpusAccess.PUB);
testDeleteQueryByName(qName, testUser, testUser);
}
-
+
@Test
- public void testCreateQueryMissingQueryLanguage () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"QUERY\""
- + ",\"query\": \"Sohn\"}";
-
+ public void testCreateQueryMissingQueryLanguage() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"query\": \"Sohn\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("queryLanguage is null", node.at("/errors/0/1").asText());
- assertEquals("queryLanguage", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "queryLanguage is null");
+ assertEquals(node.at("/errors/0/2").asText(), "queryLanguage");
}
-
+
@Test
- public void testCreateQueryMissingQuery () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"QUERY\""
- + ",\"queryLanguage\": \"poliqarp\"}";
-
+ public void testCreateQueryMissingQuery() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"QUERY\"" + ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("query is null", node.at("/errors/0/1").asText());
- assertEquals("query", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "query is null");
+ assertEquals(node.at("/errors/0/2").asText(), "query");
}
-
+
@Test
- public void testCreateQueryMissingResourceType () throws KustvaktException {
- String json = "{\"query\": \"Wind\""
- + ",\"queryLanguage\": \"poliqarp\"}";
-
+ public void testCreateQueryMissingResourceType() throws KustvaktException {
+ String json = "{\"query\": \"Wind\"" + ",\"queryLanguage\": \"poliqarp\"}";
String qName = "new_query";
- Response response = target().path(API_VERSION).path("query")
- .path("~" + testUser).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("query").path("~" + testUser).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("type is null", node.at("/errors/0/1").asText());
- assertEquals("type", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "type is null");
+ assertEquals(node.at("/errors/0/2").asText(), "type");
}
-
- private void testDeleteQueryByName (String qName, String qCreator, String username)
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .path("~" + qCreator).path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
+ private void testDeleteQueryByName(String qName, String qCreator, String username) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").path("~" + qCreator).path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
-
- @Test
- public void testDeleteQueryUnauthorized () throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .path("~dory").path("dory-q")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .delete();
+ @Test
+ public void testDeleteQueryUnauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").path("~dory").path("dory-q").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).delete();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser,
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
}
-
- private void testDeleteSystemQueryUnauthorized (String qName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .path("~system").path(qName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .delete();
+ private void testDeleteSystemQueryUnauthorized(String qName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").path("~system").path(qName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).delete();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser,
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
}
-
- @Test
- public void testDeleteNonExistingQuery () throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .path("~dory").path("non-existing-query")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .delete();
+ @Test
+ public void testDeleteNonExistingQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").path("~dory").path("non-existing-query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("Query dory/non-existing-query is not found.",
- node.at("/errors/0/1").asText());
- assertEquals("dory/non-existing-query",
- node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Query dory/non-existing-query is not found.");
+ assertEquals(node.at("/errors/0/2").asText(), "dory/non-existing-query");
}
@Test
- public void testListAvailableQueryForDory () throws
- ProcessingException, KustvaktException {
+ public void testListAvailableQueryForDory() throws ProcessingException, KustvaktException {
JsonNode node = testListAvailableQuery("dory");
assertEquals(2, node.size());
}
@Test
- public void testListAvailableQueryForPearl ()
- throws ProcessingException,
- KustvaktException {
-
+ public void testListAvailableQueryForPearl() throws ProcessingException, KustvaktException {
JsonNode node = testListAvailableQuery("pearl");
-
assertEquals(1, node.size());
- assertEquals("system-q", node.at("/0/name").asText());
- assertEquals(ResourceType.SYSTEM.displayName(),
- node.at("/0/type").asText());
- assertEquals("\"system\" query", node.at("/0/description").asText());
- assertEquals("[]", node.at("/0/query").asText());
+ assertEquals(node.at("/0/name").asText(), "system-q");
+ assertEquals(ResourceType.SYSTEM.displayName(), node.at("/0/type").asText());
+ assertEquals(node.at("/0/description").asText(), "\"system\" query");
+ assertEquals(node.at("/0/query").asText(), "[]");
assertEquals(CorpusAccess.FREE.name(), node.at("/0/requiredAccess").asText());
-// assertEquals("koral:token", node.at("/0/koralQuery/@type").asText());
+ // assertEquals("koral:token", node.at("/0/koralQuery/@type").asText());
}
- private JsonNode testListAvailableQuery (String username)
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("query")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ private JsonNode testListAvailableQuery(String username) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("query").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
index 00a8077..4000d3c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QueryReferenceSearchTest.java
@@ -1,17 +1,28 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;
-public class QueryReferenceSearchTest {
+/*@Test
+ public void testSearchWithVCRefEqual () throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search")
+ .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
+ .queryParam("cq", "referTo \"dory/dory-q\"")
+ .get();
+ String ent = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(ent);
+ assertTrue(node.at("/matches").size() > 0);
+ }
+*/
+public class QueryReferenceSearchTest {
/*@Test
public void testSearchWithVCRefEqual () throws KustvaktException {
Response response = target().path(API_VERSION).path("search")
@@ -23,5 +34,5 @@
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
}
-*/
+*/
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
index 23c7257..bacf602 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/QuerySerializationControllerTest.java
@@ -1,161 +1,87 @@
package de.ids_mannheim.korap.web.controller;
-/**
- * @author hanl, margaretha
- * @lastUpdate 19/04/2017
- * EM: FIX ME: Database restructure
- */
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Iterator;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;
-
// EM: The API is disabled
-@Ignore
+@Disabled
public class QuerySerializationControllerTest extends SpringJerseyTest {
@Test
- public void testQuerySerializationFilteredPublic ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("corpus/WPD13/query").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testQuerySerializationFilteredPublic() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/WPD13/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("corpusSigle", node.at("/collection/key").asText());
- assertEquals("WPD13", node.at("/collection/value").asText());
+ assertEquals(node.at("/collection/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/value").asText(), "WPD13");
}
-
-
@Test
- public void testQuerySerializationUnexistingResource ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("corpus/ZUW19/query")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("context", "base/s:s")
- .request()
- .method("GET");
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testQuerySerializationUnexistingResource() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/ZUW19/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals("[Cannot found public Corpus with ids: [ZUW19]]",
- node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [ZUW19]]");
}
-
@Test
- public void testQuerySerializationWithNonPublicCorpus ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("corpus/BRZ10/query").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
- .request()
- .method("GET");
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testQuerySerializationWithNonPublicCorpus() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/BRZ10/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals("[Cannot found public Corpus with ids: [BRZ10]]",
- node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [BRZ10]]");
}
-
@Test
- public void testQuerySerializationWithAuthentication ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("corpus/BRZ10/query").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testQuerySerializationWithAuthentication() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/BRZ10/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("corpusSigle", node.at("/collection/key").asText());
- assertEquals("BRZ10", node.at("/collection/value").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/value").asText(), "BRZ10");
}
-
@Test
- public void testQuerySerializationWithNewCollection ()
- throws KustvaktException {
+ public void testQuerySerializationWithNewCollection() throws KustvaktException {
// Add Virtual Collection
- Response response = target().path(API_VERSION)
-
- .path("virtualcollection").queryParam("filter", "false")
- .queryParam("query",
- "creationDate since 1775 & corpusSigle=GOE")
- .queryParam("name", "Weimarer Werke")
- .queryParam("description", "Goethe-Werke in Weimar (seit 1775)")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .post(Entity.json(""));
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ Response response = target().path(API_VERSION).path("virtualcollection").queryParam("filter", "false").queryParam("query", "creationDate since 1775 & corpusSigle=GOE").queryParam("name", "Weimarer Werke").queryParam("description", "Goethe-Werke in Weimar (seit 1775)").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(""));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertTrue(node.isObject());
- assertEquals("Weimarer Werke", node.path("name").asText());
-
+ assertEquals(node.path("name").asText(), "Weimarer Werke");
// Get virtual collections
- response = target().path(API_VERSION)
-
- .path("collection")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("collection").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
ent = response.readEntity(String.class);
node = JsonUtils.readTree(ent);
assertNotNull(node);
-
Iterator<JsonNode> it = node.elements();
String id = null;
while (it.hasNext()) {
@@ -165,124 +91,65 @@
}
assertNotNull(id);
assertFalse(id.isEmpty());
-
// query serialization service
- response = target().path(API_VERSION)
-
- .path("collection").path(id).path("query")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("context", "base/s:s")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("collection").path(id).path("query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
ent = response.readEntity(String.class);
node = JsonUtils.readTree(ent);
assertNotNull(node);
-// System.out.println("NODE " + ent);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("koral:doc",
- node.at("/collection/operands/0/@type").asText());
- assertEquals("creationDate",
- node.at("/collection/operands/0/key").asText());
- assertEquals("1775", node.at("/collection/operands/0/value").asText());
- assertEquals("type:date",
- node.at("/collection/operands/0/type").asText());
- assertEquals("match:geq",
- node.at("/collection/operands/0/match").asText());
-
- assertEquals("koral:doc",
- node.at("/collection/operands/1/@type").asText());
- assertEquals("corpusSigle",
- node.at("/collection/operands/1/key").asText());
- assertEquals("GOE", node.at("/collection/operands/1/value").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/1/match").asText());
+ // System.out.println("NODE " + ent);
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "creationDate");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "1775");
+ assertEquals(node.at("/collection/operands/0/type").asText(), "type:date");
+ assertEquals(node.at("/collection/operands/0/match").asText(), "match:geq");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "GOE");
+ assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
}
-
@Test
- public void testQuerySerializationOfVirtualCollection ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("collection/GOE-VC/query").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp").queryParam("context", "base/s:s")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testQuerySerializationOfVirtualCollection() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection/GOE-VC/query").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "base/s:s").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("koral:doc",
- node.at("/collection/operands/0/@type").asText());
- assertEquals("corpusSigle",
- node.at("/collection/operands/0/key").asText());
- assertEquals("GOE", node.at("/collection/operands/0/value").asText());
- assertEquals("koral:doc",
- node.at("/collection/operands/1/@type").asText());
- assertEquals("creationDate",
- node.at("/collection/operands/1/key").asText());
- assertEquals("1810-01-01",
- node.at("/collection/operands/1/value").asText());
-
+ assertEquals(node.at("/collection/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/0/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "GOE");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "creationDate");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "1810-01-01");
}
-
@Test
- public void testMetaQuerySerialization () throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("query").queryParam("context", "sentence")
- .queryParam("count", "20").queryParam("page", "5")
- .queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]")
- .queryParam("ql", "poliqarp")
- .request()
- .method("GET");
- assertEquals(response.getStatus(),
- Status.OK.getStatusCode());
-
+ public void testMetaQuerySerialization() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").queryParam("context", "sentence").queryParam("count", "20").queryParam("page", "5").queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().method("GET");
+ assertEquals(response.getStatus(), Status.OK.getStatusCode());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
- assertEquals("sentence", node.at("/meta/context").asText());
+ assertEquals(node.at("/meta/context").asText(), "sentence");
assertEquals(20, node.at("/meta/count").asInt());
assertEquals(5, node.at("/meta/startPage").asInt());
assertEquals(true, node.at("/meta/cutOff").asBoolean());
-
- assertEquals("koral:term", node.at("/query/wrap/@type").asText());
- assertEquals("pos", node.at("/query/wrap/layer").asText());
- assertEquals("match:eq", node.at("/query/wrap/match").asText());
- assertEquals("ADJA", node.at("/query/wrap/key").asText());
+ assertEquals(node.at("/query/wrap/@type").asText(), "koral:term");
+ assertEquals(node.at("/query/wrap/layer").asText(), "pos");
+ assertEquals(node.at("/query/wrap/match").asText(), "match:eq");
+ assertEquals(node.at("/query/wrap/key").asText(), "ADJA");
}
-
@Test
- public void testMetaQuerySerializationWithOffset ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("query").queryParam("context", "sentence")
- .queryParam("count", "20").queryParam("page", "5")
- .queryParam("offset", "2").queryParam("cutoff", "true")
- .queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp")
- .request()
- .method("GET");
- assertEquals(response.getStatus(),
- Status.OK.getStatusCode());
-
+ public void testMetaQuerySerializationWithOffset() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").queryParam("context", "sentence").queryParam("count", "20").queryParam("page", "5").queryParam("offset", "2").queryParam("cutoff", "true").queryParam("q", "[pos=ADJA]").queryParam("ql", "poliqarp").request().method("GET");
+ assertEquals(response.getStatus(), Status.OK.getStatusCode());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
- assertEquals("sentence", node.at("/meta/context").asText());
+ assertEquals(node.at("/meta/context").asText(), "sentence");
assertEquals(20, node.at("/meta/count").asInt());
assertEquals(2, node.at("/meta/startIndex").asInt());
assertEquals(true, node.at("/meta/cutOff").asBoolean());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
index 7e9fba6..4f0ce21 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/ResourceInfoControllerTest.java
@@ -1,18 +1,16 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -22,91 +20,59 @@
/**
* @author hanl, margaretha
* @lastUpdate 19/04/2017
- * EM: FIX ME: Database restructure
+ * EM: FIX ME: Database restructure
*/
-@Ignore
+@Disabled
public class ResourceInfoControllerTest extends SpringJerseyTest {
@Test
- public void testGetPublicVirtualCollectionInfo () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("collection")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetPublicVirtualCollectionInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertEquals(1, node.size());
}
-
@Test
- public void testGetVirtualCollectionInfoWithAuthentication ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("collection")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testGetVirtualCollectionInfoWithAuthentication() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertNotNull(node);
assertTrue(node.isArray());
assertEquals(3, node.size());
}
-
@Test
- public void testGetVirtualCollectionInfoById () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("collection").path("GOE-VC")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetVirtualCollectionInfoById() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection").path("GOE-VC").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
- assertEquals("Goethe Virtual Collection", node.path("name").asText());
- assertEquals("Goethe works from 1810",
- node.path("description").asText());
+ assertEquals(node.path("name").asText(), "Goethe Virtual Collection");
+ assertEquals(node.path("description").asText(), "Goethe works from 1810");
}
@Test
- public void testGetVirtualCollectionInfoByIdUnauthorized ()
- throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("collection").path("WPD15-VC")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testGetVirtualCollectionInfoByIdUnauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("collection").path("WPD15-VC").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals(
- "[Cannot found public VirtualCollection with ids: [WPD15-VC]]",
- node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public VirtualCollection with ids: [WPD15-VC]]");
}
@Test
- public void testGetPublicCorporaInfo () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetPublicCorporaInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
@@ -114,49 +80,33 @@
assertEquals(2, node.size());
}
-
@Test
- public void testGetCorpusInfoById () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus").path("WPD13")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetCorpusInfoById() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("WPD13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
// System.out.println(ent);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertTrue(node.isObject());
- assertEquals("WPD13", node.path("id").asText());
+ assertEquals(node.path("id").asText(), "WPD13");
}
-
@Test
- public void testGetCorpusInfoById2 () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus").path("GOE")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetCorpusInfoById2() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("GOE").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertTrue(node.isObject());
- assertEquals("GOE", node.path("id").asText());
+ assertEquals(node.path("id").asText(), "GOE");
}
-
@Test
- public void testGetPublicFoundriesInfo () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("foundry")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetPublicFoundriesInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("foundry").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
@@ -164,61 +114,41 @@
assertEquals(10, node.size());
}
-
@Test
- public void testGetFoundryInfoById () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("foundry").path("tt")
- .request()
- .get();
+ public void testGetFoundryInfoById() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("foundry").path("tt").request().get();
String ent = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
}
-
@Test
- public void testGetUnexistingCorpusInfo () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus").path("ZUW19")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testGetUnexistingCorpusInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("ZUW19").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals("[Cannot found public Corpus with ids: [ZUW19]]",
- node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [ZUW19]]");
}
-
// EM: queries for an unauthorized corpus get the same responses /
// treatment as
// asking for an unexisting corpus info. Does it need a specific
// exception instead?
@Test
- public void testGetUnauthorizedCorpusInfo () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus").path("BRZ10")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testGetUnauthorizedCorpusInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus").path("BRZ10").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.size());
assertEquals(101, node.at("/errors/0/0").asInt());
- assertEquals("[Cannot found public Corpus with ids: [BRZ10]]",
- node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[Cannot found public Corpus with ids: [BRZ10]]");
}
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
index d592ccf..0beb2ab 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchControllerTest.java
@@ -1,21 +1,21 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
@@ -30,28 +30,21 @@
/**
* @author hanl, margaretha
* @lastUpdate 18/03/2019
- *
*/
public class SearchControllerTest extends SpringJerseyTest {
@Autowired
private KustvaktConfiguration config;
- private JsonNode requestSearchWithFields(String fields) throws KustvaktException{
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("fields", fields)
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ private JsonNode requestSearchWithFields(String fields) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", fields).queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
return node;
}
-
- private String createJsonQuery(){
+
+ private String createJsonQuery() {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
s.setCollection("corpusSigle=GOE");
@@ -60,99 +53,67 @@
}
@Test
- public void testApiWelcomeMessage () {
- Response response = target().path(API_VERSION).path("")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
-
+ public void testApiWelcomeMessage() {
+ Response response = target().path(API_VERSION).path("").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
String message = response.readEntity(String.class);
assertEquals(message, config.getApiWelcomeMessage());
}
@Test
- public void testSearchShowTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("show-tokens", true).request()
- .get();
+ public void testSearchShowTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("show-tokens", true).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(3, node.at("/matches/0/tokens").size());
assertFalse(node.at("/matches/0/snippet").isMissingNode());
}
-
+
@Test
- public void testSearchDisableSnippet () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("show-snippet", false)
- .queryParam("show-tokens", true)
- .request()
- .get();
+ public void testSearchDisableSnippet() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("show-snippet", false).queryParam("show-tokens", true).request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/matches/0/snippet").isMissingNode());
assertEquals(3, node.at("/matches/0/tokens").size());
}
-
+
@Test
- public void testSearchWithField () throws KustvaktException {
+ public void testSearchWithField() throws KustvaktException {
JsonNode node = requestSearchWithFields("author");
assertNotEquals(0, node.at("/matches").size());
- assertEquals("[\"author\"]",
- node.at("/meta/fields").toString());
-
+ assertEquals(node.at("/meta/fields").toString(), "[\"author\"]");
assertTrue(node.at("/matches/0/tokens").isMissingNode());
}
-
+
@Test
- public void testSearchWithMultipleFields () throws KustvaktException {
+ public void testSearchWithMultipleFields() throws KustvaktException {
JsonNode node = requestSearchWithFields("author, title");
assertNotEquals(0, node.at("/matches").size());
- assertEquals("[\"author\",\"title\"]",
- node.at("/meta/fields").toString());
+ assertEquals(node.at("/meta/fields").toString(), "[\"author\",\"title\"]");
}
-
+
@Test
- public void testSearchQueryPublicCorpora () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .request()
- .accept(MediaType.APPLICATION_JSON).get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryPublicCorpora() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("availability", node.at("/collection/key").asText());
- assertEquals("CC-BY.*", node.at("/collection/value").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "availability");
+ assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
}
@Test
- public void testSearchQueryFailure () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der").queryParam("ql", "poliqarp")
- .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
- .queryParam("count", "13")
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ public void testSearchQueryFailure() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").queryParam("count", "13").request().accept(MediaType.APPLICATION_JSON).get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
@@ -164,342 +125,209 @@
}
@Test
- public void testSearchQueryWithMeta () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=Bachelor]").queryParam("ql", "poliqarp")
- .queryParam("cutoff", "true").queryParam("count", "5")
- .queryParam("page", "1").queryParam("context", "40-t,30-t")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryWithMeta() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=Bachelor]").queryParam("ql", "poliqarp").queryParam("cutoff", "true").queryParam("count", "5").queryParam("page", "1").queryParam("context", "40-t,30-t").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertTrue(node.at("/meta/cutOff").asBoolean());
assertEquals(5, node.at("/meta/count").asInt());
assertEquals(0, node.at("/meta/startIndex").asInt());
- assertEquals("token", node.at("/meta/context/left/0").asText());
+ assertEquals(node.at("/meta/context/left/0").asText(), "token");
assertEquals(40, node.at("/meta/context/left/1").asInt());
assertEquals(30, node.at("/meta/context/right/1").asInt());
assertEquals(-1, node.at("/meta/totalResults").asInt());
- for (String path : new String[] { "/meta/count", "/meta/startIndex",
- "/meta/context/left/1", "/meta/context/right/1",
- "/meta/totalResults", "/meta/itemsPerPage" }) {
- assertTrue(path + " should be a number", node.at(path).isNumber());
+ for (String path : new String[]{"/meta/count", "/meta/startIndex", "/meta/context/left/1", "/meta/context/right/1", "/meta/totalResults", "/meta/itemsPerPage"}) {
+ assertTrue(node.at(path).isNumber(), path + " should be a number");
}
}
@Test
- public void testSearchQueryFreeExtern () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryFreeExtern() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("availability", node.at("/collection/key").asText());
- assertEquals("CC-BY.*", node.at("/collection/value").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "availability");
+ assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
}
@Test
- public void testSearchQueryFreeIntern () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryFreeIntern() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("availability", node.at("/collection/key").asText());
- assertEquals("CC-BY.*", node.at("/collection/value").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "availability");
+ assertEquals(node.at("/collection/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
}
@Test
- public void testSearchQueryExternAuthorized () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryExternAuthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
// System.out.println(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("ACA.*",
- node.at("/collection/operands/1/operands/0/value").asText());
- assertEquals("QAO-NC",
- node.at("/collection/operands/1/operands/1/value").asText());
- assertEquals("operation:or", node.at("/collection/operation").asText());
- assertEquals("availability(PUB)",
- node.at("/collection/rewrites/0/scope").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "ACA.*");
+ assertEquals(node.at("/collection/operands/1/operands/1/value").asText(), "QAO-NC");
+ assertEquals(node.at("/collection/operation").asText(), "operation:or");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
}
@Test
- public void testSearchQueryInternAuthorized () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32")
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchQueryInternAuthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).header(HttpHeaders.X_FORWARDED_FOR, "172.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
-// System.out.println(node);
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("ACA.*",
- node.at("/collection/operands/1/operands/0/value").asText());
- assertEquals("QAO-NC",
- node.at("/collection/operands/1/operands/1/operands/0/value")
- .asText());
- assertEquals("QAO.*",
- node.at("/collection/operands/1/operands/1/operands/1/value")
- .asText());
- assertEquals("operation:or", node.at("/collection/operation").asText());
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
+ // System.out.println(node);
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/value").asText(), "ACA.*");
+ assertEquals(node.at("/collection/operands/1/operands/1/operands/0/value").asText(), "QAO-NC");
+ assertEquals(node.at("/collection/operands/1/operands/1/operands/1/value").asText(), "QAO.*");
+ assertEquals(node.at("/collection/operation").asText(), "operation:or");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
}
-
+
@Test
- public void testSearchWithCorpusQuery () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "corpusTitle=gingko")
- .request()
- .accept(MediaType.APPLICATION_JSON).get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithCorpusQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "corpusTitle=gingko").request().accept(MediaType.APPLICATION_JSON).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
assertEquals(2, node.at("/collection/operands").size());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
-
- assertEquals("gingko",
- node.at("/collection/operands/1/value").asText());
- assertEquals("match:eq",
- node.at("/collection/operands/1/match").asText());
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "gingko");
+ assertEquals(node.at("/collection/operands/1/match").asText(), "match:eq");
assertTrue(node.at("/collection/operands/1/type").isMissingNode());
}
@Test
- public void testSearchQueryWithCollectionQueryAuthorizedWithoutIP ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("cq", "textClass=politik & corpusSigle=BRZ10")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchQueryWithCollectionQueryAuthorizedWithoutIP() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", "textClass=politik & corpusSigle=BRZ10").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertNotNull(node);
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
// EM: double AND operations
- assertEquals("availability",
- node.at("/collection/operands/0/key").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("textClass",
- node.at("/collection/operands/1/operands/0/key").asText());
- assertEquals("corpusSigle",
- node.at("/collection/operands/1/operands/1/key").asText());
+ assertEquals(node.at("/collection/operands/0/key").asText(), "availability");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/operands/0/key").asText(), "textClass");
+ assertEquals(node.at("/collection/operands/1/operands/1/key").asText(), "corpusSigle");
}
@Test
- @Ignore
- public void testSearchQueryAuthorizedWithoutIP () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Disabled
+ public void testSearchQueryAuthorizedWithoutIP() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("CC-BY.*",
- node.at("/collection/operands/0/value").asText());
- assertEquals("ACA.*", node.at("/collection/operands/1/value").asText());
- assertEquals("operation:or", node.at("/collection/operation").asText());
- assertEquals("availability(PUB)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "ACA.*");
+ assertEquals(node.at("/collection/operation").asText(), "operation:or");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
}
-
+
@Test
- public void testSearchWithInvalidPage () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "0")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testSearchWithInvalidPage() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "0").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("page must start from 1",node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "page must start from 1");
}
@Test
- public void testSearchSentenceMeta () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("context", "sentence")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchSentenceMeta() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("context", "sentence").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("base/s:s", node.at("/meta/context").asText());
- assertNotEquals("${project.version}", "/meta/version");
+ assertEquals(node.at("/meta/context").asText(), "base/s:s");
+ assertNotEquals("/meta/version", "${project.version}");
}
-// EM: The API is disabled
- @Ignore
+ // EM: The API is disabled
+ @Disabled
@Test
- public void testSearchSimpleCQL () throws KustvaktException {
+ public void testSearchSimpleCQL() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("(der) or (das)", "CQL");
-
- Response response = target().path(API_VERSION).path("search")
- .request()
- .post(Entity.json(s.toJSON()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
// assertEquals(17027, node.at("/meta/totalResults").asInt());
}
-// EM: The API is disabled
+ // EM: The API is disabled
@Test
- @Ignore
- public void testSearchRawQuery () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .request()
- .post(Entity.json(createJsonQuery()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Disabled
+ public void testSearchRawQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request().post(Entity.json(createJsonQuery()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
-
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
}
-
-// EM: The API is disabled
- @Test
- @Ignore
- public void testSearchPostAll () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32")
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .post(Entity.json(createJsonQuery()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- String ent = response.readEntity(String.class);
+ // EM: The API is disabled
+ @Test
+ @Disabled
+ public void testSearchPostAll() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request().header(HttpHeaders.X_FORWARDED_FOR, "10.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(createJsonQuery()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
-
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
}
-
-// EM: The API is disabled
- @Test
- @Ignore
- public void testSearchPostPublic () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("kustvakt",
- "kustvakt2015"))
- .post(Entity.json(createJsonQuery()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- String ent = response.readEntity(String.class);
+ // EM: The API is disabled
+ @Test
+ @Disabled
+ public void testSearchPostPublic() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("kustvakt", "kustvakt2015")).post(Entity.json(createJsonQuery()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
assertNotEquals(0, node.path("matches").size());
-
- assertEquals("availability(PUB)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(PUB)");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
index f35260a..3c2d277 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchNetworkEndpointTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
@@ -8,19 +8,18 @@
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
-
import javax.ws.rs.core.Response.Status;
import org.apache.commons.io.IOUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Header;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
@@ -35,97 +34,58 @@
private KustvaktConfiguration config;
private ClientAndServer mockServer;
+
private MockServerClient mockClient;
private int port = 6081;
- private String searchResult;
- private String endpointURL = "http://localhost:"+port+"/searchEndpoint";
- public SearchNetworkEndpointTest () throws IOException {
- searchResult = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "network-output/search-result.jsonld"),
- StandardCharsets.UTF_8);
+ private String searchResult;
+
+ private String endpointURL = "http://localhost:" + port + "/searchEndpoint";
+
+ public SearchNetworkEndpointTest() throws IOException {
+ searchResult = IOUtils.toString(ClassLoader.getSystemResourceAsStream("network-output/search-result.jsonld"), StandardCharsets.UTF_8);
}
-
- @Before
- public void startMockServer () {
+ @BeforeEach
+ public void startMockServer() {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
-
- @After
- public void stopMockServer () {
+ @AfterEach
+ public void stopMockServer() {
mockServer.stop();
}
-
@Test
- public void testSearchNetwork ()
- throws IOException, KustvaktException, URISyntaxException {
+ public void testSearchNetwork() throws IOException, KustvaktException, URISyntaxException {
config.setNetworkEndpointURL(endpointURL);
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/searchEndpoint")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(searchResult).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ mockClient.reset().when(request().withMethod("POST").withPath("/searchEndpoint").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(searchResult).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2, node.at("/matches").size());
}
-
@Test
- public void testSearchWithUnknownURL ()
- throws IOException, KustvaktException {
+ public void testSearchWithUnknownURL() throws IOException, KustvaktException {
config.setNetworkEndpointURL("http://localhost:1040/search");
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-
- @Test
- public void testSearchWithUnknownHost () throws KustvaktException {
- config.setNetworkEndpointURL("http://search.com");
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
+ @Test
+ public void testSearchWithUnknownHost() throws KustvaktException {
+ config.setNetworkEndpointURL("http://search.com");
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
index 10149d3..7f11f9a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPipeTest.java
@@ -1,7 +1,7 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
@@ -15,18 +15,17 @@
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
-
import javax.ws.rs.core.Response.Status;
import org.apache.commons.io.IOUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Header;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -37,351 +36,174 @@
public class SearchPipeTest extends SpringJerseyTest {
private ClientAndServer mockServer;
+
private MockServerClient mockClient;
private int port = 6071;
+
private String pipeJson, pipeWithParamJson;
- private String glemmUri = "http://localhost:"+port+"/glemm";
- public SearchPipeTest () throws URISyntaxException, IOException {
- pipeJson = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "pipe-output/test-pipes.jsonld"),
- StandardCharsets.UTF_8);
+ private String glemmUri = "http://localhost:" + port + "/glemm";
- pipeWithParamJson = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "pipe-output/with-param.jsonld"),
- StandardCharsets.UTF_8);
+ public SearchPipeTest() throws URISyntaxException, IOException {
+ pipeJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/test-pipes.jsonld"), StandardCharsets.UTF_8);
+ pipeWithParamJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/with-param.jsonld"), StandardCharsets.UTF_8);
}
- @Before
- public void startMockServer () {
+ @BeforeEach
+ public void startMockServer() {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
- @After
- public void stopMockServer () {
+ @AfterEach
+ public void stopMockServer() {
mockServer.stop();
}
@Test
- public void testMockServer () throws IOException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/test")
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody("{test}").withStatusCode(200));
-
- URL url = new URL("http://localhost:"+port+"/test");
+ public void testMockServer() throws IOException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/test").withHeader(new Header("Content-Type", "application/json; charset=utf-8"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody("{test}").withStatusCode(200));
+ URL url = new URL("http://localhost:" + port + "/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type",
- "application/json; charset=UTF-8");
+ connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
-
String json = "{\"name\" : \"dory\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length);
}
-
assertEquals(200, connection.getResponseCode());
-
- BufferedReader br = new BufferedReader(
- new InputStreamReader(connection.getInputStream(), "utf-8"));
- assertEquals("{test}", br.readLine());
-
+ BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
+ assertEquals(br.readLine(), "{test}");
}
@Test
- public void testSearchWithPipes ()
- throws IOException, KustvaktException, URISyntaxException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithPipes() throws IOException, KustvaktException, URISyntaxException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
-
assertEquals(1, node.at("/collection/rewrites").size());
- assertEquals("operation:insertion",
- node.at("/collection/rewrites/0/operation").asText());
- assertEquals("availability(FREE)",
- node.at("/collection/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/collection/rewrites/0/operation").asText(), "operation:insertion");
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(FREE)");
node = node.at("/query/wrap/rewrites");
assertEquals(2, node.size());
- assertEquals("Glemm", node.at("/0/src").asText());
- assertEquals("operation:override", node.at("/0/operation").asText());
- assertEquals("key", node.at("/0/scope").asText());
-
- assertEquals("Kustvakt", node.at("/1/src").asText());
- assertEquals("operation:injection", node.at("/1/operation").asText());
- assertEquals("foundry", node.at("/1/scope").asText());
+ assertEquals(node.at("/0/src").asText(), "Glemm");
+ assertEquals(node.at("/0/operation").asText(), "operation:override");
+ assertEquals(node.at("/0/scope").asText(), "key");
+ assertEquals(node.at("/1/src").asText(), "Kustvakt");
+ assertEquals(node.at("/1/operation").asText(), "operation:injection");
+ assertEquals(node.at("/1/scope").asText(), "foundry");
}
@Test
- public void testSearchWithUrlEncodedPipes ()
- throws IOException, KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
+ public void testSearchWithUrlEncodedPipes() throws IOException, KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
glemmUri = URLEncoder.encode(glemmUri, "utf-8");
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri)
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithMultiplePipes () throws KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withQueryStringParameter("param").withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeWithParamJson).withStatusCode(200));
-
+ public void testSearchWithMultiplePipes() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withQueryStringParameter("param").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeWithParamJson).withStatusCode(200));
String glemmUri2 = glemmUri + "?param=blah";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri + "," + glemmUri2)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + "," + glemmUri2).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(3, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithUnknownURL ()
- throws IOException, KustvaktException {
- String url =
- target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", url)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithUnknownURL() throws IOException, KustvaktException {
+ String url = target().getUri().toString() + API_VERSION + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("404 Not Found", node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "404 Not Found");
}
@Test
- public void testSearchWithUnknownHost () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", "http://glemm")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithUnknownHost() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://glemm").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("glemm", node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "glemm");
}
@Test
- public void testSearchUnsupportedMediaType () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/non-json-pipe"))
- .respond(response().withStatusCode(415));
-
- String pipeUri = "http://localhost:"+port+"/non-json-pipe";
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchUnsupportedMediaType() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/non-json-pipe")).respond(response().withStatusCode(415));
+ String pipeUri = "http://localhost:" + port + "/non-json-pipe";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("415 Unsupported Media Type",
- node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "415 Unsupported Media Type");
}
@Test
- public void testSearchWithMultiplePipeWarnings () throws KustvaktException {
- String url =
- target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", url + "," + "http://glemm")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithMultiplePipeWarnings() throws KustvaktException {
+ String url = target().getUri().toString() + API_VERSION + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url + "," + "http://glemm").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2, node.at("/warnings").size());
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
assertEquals(url, node.at("/warnings/0/2").asText());
- assertEquals("404 Not Found", node.at("/warnings/0/3").asText());
-
+ assertEquals(node.at("/warnings/0/3").asText(), "404 Not Found");
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/1/0").asInt());
- assertEquals("http://glemm", node.at("/warnings/1/2").asText());
- assertEquals("glemm", node.at("/warnings/1/3").asText());
-
+ assertEquals(node.at("/warnings/1/2").asText(), "http://glemm");
+ assertEquals(node.at("/warnings/1/3").asText(), "glemm");
}
@Test
- public void testSearchWithInvalidJsonResponse () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/invalid-response")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response().withBody("{blah:}").withStatusCode(200)
- .withHeaders(new Header("Content-Type",
- "application/json; charset=utf-8")));
-
- String pipeUri = "http://localhost:"+port+"/invalid-response";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchWithInvalidJsonResponse() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/invalid-response").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("{blah:}").withStatusCode(200).withHeaders(new Header("Content-Type", "application/json; charset=utf-8")));
+ String pipeUri = "http://localhost:" + port + "/invalid-response";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithPlainTextResponse () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/plain-text")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response().withBody("blah").withStatusCode(200));
-
- String pipeUri = "http://localhost:"+port+"/plain-text";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchWithPlainTextResponse() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/plain-text").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("blah").withStatusCode(200));
+ String pipeUri = "http://localhost:" + port + "/plain-text";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithMultipleAndUnknownPipes ()
- throws KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", "http://unknown" + "," + glemmUri)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithMultipleAndUnknownPipes() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://unknown" + "," + glemmUri).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
assertTrue(node.at("/warnings").isMissingNode());
-
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri + ",http://unknown")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + ",http://unknown").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
index 7281f28..d49756e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchPublicMetadataTest.java
@@ -1,16 +1,16 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response.Status;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -23,164 +23,93 @@
public class SearchPublicMetadataTest extends SpringJerseyTest {
@Test
- public void testSearchPublicMetadata () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadata() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
@Test
- public void testSearchPublicMetadataExtern () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadataExtern() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
-
+
@Test
- public void testSearchPublicMetadataWithCustomFields () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("fields", "author,title")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadataWithCustomFields() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
-
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
- assertEquals("Goethe, Johann Wolfgang von",
- node.at("/matches/0/author").asText());
- assertEquals("Italienische Reise",
- node.at("/matches/0/title").asText());
-// assertEquals(3, node.at("/matches/0").size());
+ assertEquals(node.at("/matches/0/author").asText(), "Goethe, Johann Wolfgang von");
+ assertEquals(node.at("/matches/0/title").asText(), "Italienische Reise");
+ // assertEquals(3, node.at("/matches/0").size());
}
-
+
@Test
- public void testSearchPublicMetadataWithNonPublicField () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("fields", "author,title,snippet")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadataWithNonPublicField() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title,snippet").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED,
- node.at("/warnings/0/0").asInt());
- assertEquals("The requested non public fields are ignored",
- node.at("/warnings/0/1").asText());
- assertEquals("snippet",
- node.at("/warnings/0/2").asText());
+ assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "The requested non public fields are ignored");
+ assertEquals(node.at("/warnings/0/2").asText(), "snippet");
}
-// EM: The API is disabled
- @Ignore
+ // EM: The API is disabled
+ @Disabled
@Test
- public void testSearchPostPublicMetadata () throws KustvaktException {
+ public void testSearchPostPublicMetadata() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=der]", "poliqarp");
s.setCollection("corpusSigle=GOE");
s.setQuery("Wasser", "poliqarp");
-
MetaQueryBuilder meta = new MetaQueryBuilder();
meta.addEntry("snippets", "true");
s.setMeta(meta);
-
- Response response = target().path(API_VERSION).path("search")
- .request()
- .post(Entity.json(s.toJSON()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(ent);
- assertEquals("availability(ALL)",
- node.at("/collection/rewrites/0/scope").asText());
+ assertEquals(node.at("/collection/rewrites/0/scope").asText(), "availability(ALL)");
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
-
- @Test
- public void testSearchPublicMetadataWithSystemVC ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo system-vc")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchPublicMetadataWithSystemVC() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("cq", "referTo system-vc").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals("operation:and",
- node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
node = node.at("/collection/operands/1");
- assertEquals("koral:doc", node.at("/@type").asText());
- assertEquals("GOE", node.at("/value").asText());
- assertEquals("match:eq", node.at("/match").asText());
- assertEquals("corpusSigle", node.at("/key").asText());
-
- assertEquals("operation:deletion",
- node.at("/rewrites/0/operation").asText());
- assertEquals("@type(koral:docGroupRef)",
- node.at("/rewrites/0/scope").asText());
-
- assertEquals("operation:deletion",
- node.at("/rewrites/1/operation").asText());
- assertEquals("ref(system-vc)", node.at("/rewrites/1/scope").asText());
-
- assertEquals("operation:insertion",
- node.at("/rewrites/2/operation").asText());
+ assertEquals(node.at("/@type").asText(), "koral:doc");
+ assertEquals(node.at("/value").asText(), "GOE");
+ assertEquals(node.at("/match").asText(), "match:eq");
+ assertEquals(node.at("/key").asText(), "corpusSigle");
+ assertEquals(node.at("/rewrites/0/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/rewrites/0/scope").asText(), "@type(koral:docGroupRef)");
+ assertEquals(node.at("/rewrites/1/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/rewrites/1/scope").asText(), "ref(system-vc)");
+ assertEquals(node.at("/rewrites/2/operation").asText(), "operation:insertion");
}
@Test
- public void testSearchPublicMetadataWithPrivateVC ()
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"dory/dory-vc\"")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
-
+ public void testSearchPublicMetadataWithPrivateVC() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").queryParam("access-rewrite-disabled", "true").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("guest", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/2").asText(), "guest");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
index bfebdf0..f261d01 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/SearchTokenSnippetTest.java
@@ -1,14 +1,14 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -19,65 +19,39 @@
public class SearchTokenSnippetTest extends SpringJerseyTest {
@Test
- public void testSearchWithTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("show-tokens", "true")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertTrue(node.at("/matches/0/hasSnippet").asBoolean());
assertTrue(node.at("/matches/0/hasTokens").asBoolean());
- assertTrue(node.at("/matches/0/tokens/left").size()>0);
- assertTrue(node.at("/matches/0/tokens/right").size()>0);
+ assertTrue(node.at("/matches/0/tokens/left").size() > 0);
+ assertTrue(node.at("/matches/0/tokens/right").size() > 0);
assertEquals(1, node.at("/matches/0/tokens/match").size());
}
-
- @Test
- public void testSearchWithoutTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("show-tokens", "false")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchWithoutTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "false").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertTrue(node.at("/matches/0/hasSnippet").asBoolean());
assertFalse(node.at("/matches/0/hasTokens").asBoolean());
assertTrue(node.at("/matches/0/tokens").isMissingNode());
}
-
- @Test
- public void testSearchPublicMetadataWithTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("access-rewrite-disabled", "true")
- .queryParam("show-tokens", "true")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchPublicMetadataWithTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertFalse(node.at("/matches/0/hasSnippet").asBoolean());
assertFalse(node.at("/matches/0/hasTokens").asBoolean());
assertTrue(node.at("/matches/0/snippet").isMissingNode());
assertTrue(node.at("/matches/0/tokens").isMissingNode());
-
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/warnings/0/0").asInt());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
index e2d36c6..753b7da 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/StatisticsControllerTest.java
@@ -1,18 +1,17 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import de.ids_mannheim.korap.config.SpringJerseyTest;
@@ -20,260 +19,150 @@
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.utils.JsonUtils;
-/**
+/**
* @author margaretha, diewald
- *
*/
public class StatisticsControllerTest extends SpringJerseyTest {
@Test
- public void testGetStatisticsNoResource ()
- throws IOException, KustvaktException {
+ public void testGetStatisticsNoResource() throws IOException, KustvaktException {
String corpusQuery = "corpusSigle=WPD15";
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", corpusQuery)
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
assert Status.OK.getStatusCode() == response.getStatus();
-
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
-
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.get("documents").asInt(),0);
- assertEquals(node.get("tokens").asInt(),0);
+ assertEquals(node.get("documents").asInt(), 0);
+ assertEquals(node.get("tokens").asInt(), 0);
}
@Test
- public void testStatisticsWithCq () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithCq() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
-
+
@Test
- public void testStatisticsWithCqAndCorpusQuery () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
- .queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithCqAndCorpusQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
@Test
- public void testGetStatisticsWithcorpusQuery1 ()
- throws IOException, KustvaktException {
+ public void testGetStatisticsWithcorpusQuery1() throws IOException, KustvaktException {
String corpusQuery = "corpusSigle=GOE";
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", corpusQuery)
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
assert Status.OK.getStatusCode() == response.getStatus();
-
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.get("documents").asInt(),11);
- assertEquals(node.get("tokens").asInt(),665842);
-
- assertEquals(StatusCodes.DEPRECATED,
- node.at("/warnings/0/0").asInt());
- assertEquals("Parameter corpusQuery is deprecated in favor of cq.",
- node.at("/warnings/0/1").asText());
+ assertEquals(node.get("documents").asInt(), 11);
+ assertEquals(node.get("tokens").asInt(), 665842);
+ assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
}
-
@Test
- public void testGetStatisticsWithcorpusQuery2 ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", "creationDate since 1810")
- .request()
- .get();
+ public void testGetStatisticsWithcorpusQuery2() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate since 1810").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assert Status.OK.getStatusCode() == response.getStatus();
- assertEquals(node.get("documents").asInt(),7);
- assertEquals(node.get("tokens").asInt(),279402);
+ assertEquals(node.get("documents").asInt(), 7);
+ assertEquals(node.get("tokens").asInt(), 279402);
assertEquals(node.get("sentences").asInt(), 11047);
assertEquals(node.get("paragraphs").asInt(), 489);
}
-
@Test
- public void testGetStatisticsWithWrongcorpusQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", "creationDate geq 1810")
- .request()
- .get();
-
- assert Status.BAD_REQUEST.getStatusCode() == response
- .getStatus();
+ public void testGetStatisticsWithWrongcorpusQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate geq 1810").request().get();
+ assert Status.BAD_REQUEST.getStatusCode() == response.getStatus();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/errors/0/0").asInt(), 302);
- assertEquals(node.at("/errors/0/1").asText(),
- "Could not parse query >>> (creationDate geq 1810) <<<.");
- assertEquals(node.at("/errors/0/2").asText(),
- "(creationDate geq 1810)");
+ assertEquals(node.at("/errors/0/1").asText(), "Could not parse query >>> (creationDate geq 1810) <<<.");
+ assertEquals(node.at("/errors/0/2").asText(), "(creationDate geq 1810)");
}
-
@Test
- public void testGetStatisticsWithWrongcorpusQuery2 ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", "creationDate >= 1810")
- .request()
- .get();
-
+ public void testGetStatisticsWithWrongcorpusQuery2() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "creationDate >= 1810").request().get();
String ent = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertEquals(node.at("/errors/0/0").asInt(), 305);
- assertEquals(node.at("/errors/0/1").asText(),
- "Operator >= is not acceptable.");
+ assertEquals(node.at("/errors/0/1").asText(), "Operator >= is not acceptable.");
assertEquals(node.at("/errors/0/2").asText(), ">=");
}
-
@Test
- public void testGetStatisticsWithoutcorpusQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetStatisticsWithoutcorpusQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
-
- JsonNode node = JsonUtils.readTree(ent);
- assertEquals(11, node.at("/documents").asInt());
- assertEquals(665842, node.at("/tokens").asInt());
- assertEquals(25074, node.at("/sentences").asInt());
- assertEquals(772, node.at("/paragraphs").asInt());
- }
-
- @Test
- public void testGetStatisticsWithKoralQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{ \"collection\" : {\"@type\": "
- + "\"koral:doc\", \"key\": \"availability\", \"match\": "
- + "\"match:eq\", \"type\": \"type:regex\", \"value\": "
- + "\"CC-BY.*\"} }"));
-
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- String ent = response.readEntity(String.class);
-
- JsonNode node = JsonUtils.readTree(ent);
- assertEquals(2, node.at("/documents").asInt());
- assertEquals(72770, node.at("/tokens").asInt());
- assertEquals(2985, node.at("/sentences").asInt());
- assertEquals(128, node.at("/paragraphs").asInt());
- }
-
- @Test
- public void testGetStatisticsWithEmptyCollection ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{}"));
-
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
- String ent = response.readEntity(String.class);
- JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/errors/0/0").asInt(),
- de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
- assertEquals(node.at("/errors/0/1").asText(),
- "Collection is not found");
- }
-
- @Test
- public void testGetStatisticsWithIncorrectJson ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{ \"collection\" : }"));
-
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
- String ent = response.readEntity(String.class);
- JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Failed deserializing json object: { \"collection\" : }",
- node.at("/errors/0/1").asText());
- }
-
- @Test
- public void testGetStatisticsWithoutKoralQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .post(Entity.json(""));
-
- String ent = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
JsonNode node = JsonUtils.readTree(ent);
assertEquals(11, node.at("/documents").asInt());
assertEquals(665842, node.at("/tokens").asInt());
assertEquals(25074, node.at("/sentences").asInt());
assertEquals(772, node.at("/paragraphs").asInt());
}
-
+
+ @Test
+ public void testGetStatisticsWithKoralQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : {\"@type\": " + "\"koral:doc\", \"key\": \"availability\", \"match\": " + "\"match:eq\", \"type\": \"type:regex\", \"value\": " + "\"CC-BY.*\"} }"));
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ String ent = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(ent);
+ assertEquals(2, node.at("/documents").asInt());
+ assertEquals(72770, node.at("/tokens").asInt());
+ assertEquals(2985, node.at("/sentences").asInt());
+ assertEquals(128, node.at("/paragraphs").asInt());
+ }
+
+ @Test
+ public void testGetStatisticsWithEmptyCollection() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{}"));
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ String ent = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(ent);
+ assertEquals(node.at("/errors/0/0").asInt(), de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
+ assertEquals(node.at("/errors/0/1").asText(), "Collection is not found");
+ }
+
+ @Test
+ public void testGetStatisticsWithIncorrectJson() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : }"));
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ String ent = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(ent);
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Failed deserializing json object: { \"collection\" : }");
+ }
+
+ @Test
+ public void testGetStatisticsWithoutKoralQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().post(Entity.json(""));
+ String ent = response.readEntity(String.class);
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ JsonNode node = JsonUtils.readTree(ent);
+ assertEquals(11, node.at("/documents").asInt());
+ assertEquals(665842, node.at("/tokens").asInt());
+ assertEquals(25074, node.at("/sentences").asInt());
+ assertEquals(772, node.at("/paragraphs").asInt());
+ }
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
index 4518d1d..3055eef 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/TokenExpiryTest.java
@@ -1,9 +1,8 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
@@ -11,12 +10,10 @@
import org.apache.http.HttpStatus;
import org.apache.http.entity.ContentType;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.SpringJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -27,37 +24,26 @@
* Before running this test:
* set oauth2.access.token.expiry = 2S
* oauth2.authorization.code.expiry = 1S
- *
- * @author margaretha
*
+ * @author margaretha
*/
public class TokenExpiryTest extends SpringJerseyTest {
-
- @Ignore
+
+ @Disabled
@Test
- public void requestToken ()
- throws KustvaktException, InterruptedException, IOException {
+ public void requestToken() throws KustvaktException, InterruptedException, IOException {
Form form = new Form();
form.param("grant_type", "password");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
form.param("client_secret", "secret");
form.param("username", "dory");
form.param("password", "password");
-
- Response response = target().path(API_VERSION).path("oauth2").path("token")
- .request()
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("token").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
String token = node.at("/access_token").asText();
-
Thread.sleep(1000);
-
testRequestAuthorizationCodeAuthenticationTooOld(token);
-
Thread.sleep(1500);
testSearchWithExpiredToken(token);
}
@@ -66,53 +52,28 @@
// because sqlite needs a trigger after INSERT to
// oauth_access_token to store created_date. Before INSERT trigger
// does not work.
- private void testSearchWithExpiredToken (String token)
- throws KustvaktException, IOException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + token)
- .get();
-
+ private void testSearchWithExpiredToken(String token) throws KustvaktException, IOException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, "Bearer " + token).get();
String ent = response.readEntity(String.class);
-
- assertEquals(Status.UNAUTHORIZED.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertEquals(StatusCodes.EXPIRED, node.at("/errors/0/0").asInt());
- assertEquals("Access token is expired",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is expired");
}
// cannot be tested dynamically
- private void testRequestAuthorizationCodeAuthenticationTooOld (String token)
- throws KustvaktException {
+ private void testRequestAuthorizationCodeAuthenticationTooOld(String token) throws KustvaktException {
Form form = new Form();
form.param("response_type", "code");
form.param("client_id", "fCBbQkAyYzI4NzUxMg");
- form.param("redirect_uri",
- "https://korap.ids-mannheim.de/confidential/redirect");
+ form.param("redirect_uri", "https://korap.ids-mannheim.de/confidential/redirect");
form.param("scope", "openid");
form.param("max_age", "1");
-
- Response response =
- target().path(API_VERSION).path("oauth2").path("openid").path("authorize")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + token)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE,
- ContentType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("oauth2").path("openid").path("authorize").request().header(Attributes.AUTHORIZATION, "Bearer " + token).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_FORM_URLENCODED).post(Entity.form(form));
assertEquals(HttpStatus.SC_UNAUTHORIZED, response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.USER_REAUTHENTICATION_REQUIRED,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "User reauthentication is required because the authentication "
- + "time is too old according to max_age",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.USER_REAUTHENTICATION_REQUIRED, node.at("/errors/0/0").asInt());
+ assertEquals("User reauthentication is required because the authentication " + "time is too old according to max_age", node.at("/errors/0/1").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
index ffbc647..c135828 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserControllerTest.java
@@ -1,19 +1,16 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.net.URI;
-
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.util.MultiValueMap;
import org.springframework.web.util.UriComponentsBuilder;
-
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -24,14 +21,14 @@
public class UserControllerTest extends OAuth2TestBase {
private String username = "User\"ControllerTest";
+
private String userAuthHeader;
- public UserControllerTest () throws KustvaktException {
- userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "password");
+ public UserControllerTest() throws KustvaktException {
+ userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
}
- private OAuth2ClientJson createOAuth2Client () {
+ private OAuth2ClientJson createOAuth2Client() {
OAuth2ClientJson client = new OAuth2ClientJson();
client.setName("OWID client");
client.setType(OAuth2ClientType.PUBLIC);
@@ -40,8 +37,7 @@
return client;
}
- private String registerClient ()
- throws ProcessingException, KustvaktException {
+ private String registerClient() throws ProcessingException, KustvaktException {
OAuth2ClientJson clientJson = createOAuth2Client();
Response response = registerClient(username, clientJson);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
@@ -49,44 +45,26 @@
return clientId;
}
- private String requestOAuth2AccessToken (String clientId)
- throws KustvaktException {
- Response response = requestAuthorizationCode("code", clientId, "",
- "user_info", "", userAuthHeader);
+ private String requestOAuth2AccessToken(String clientId) throws KustvaktException {
+ Response response = requestAuthorizationCode("code", clientId, "", "user_info", "", userAuthHeader);
String code = parseAuthorizationCode(response);
-
- response =
- requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
-
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, null, code);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
String accessToken = node.at("/access_token").asText();
return accessToken;
}
@Test
- public void getUsername () throws ProcessingException, KustvaktException {
+ public void getUsername() throws ProcessingException, KustvaktException {
String clientId = registerClient();
String accessToken = requestOAuth2AccessToken(clientId);
-
- Response response = target().path(API_VERSION).path("user").path("info")
- .request()
- .header(Attributes.AUTHORIZATION, "Bearer " + accessToken)
- .get();
-
+ Response response = target().path(API_VERSION).path("user").path("info").request().header(Attributes.AUTHORIZATION, "Bearer " + accessToken).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(username, node.at("/username").asText());
-
deregisterClient(username, clientId);
}
-
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
index 33d6532..8cac40a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerAdminTest.java
@@ -1,14 +1,14 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -26,23 +26,15 @@
/**
* @author margaretha
- *
*/
public class UserGroupControllerAdminTest extends SpringJerseyTest {
private String sysAdminUser = "admin";
+
private String testUser = "group-admin";
- private JsonNode listGroup (String username)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ private JsonNode listGroup(String username) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -50,61 +42,44 @@
}
@Test
- public void testListUserGroupsUsingAdminToken () throws KustvaktException {
+ public void testListUserGroupsUsingAdminToken() throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
f.param("token", "secret");
-
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(3, node.size());
}
-
-
+
/**
* Cannot use admin token
* see
- * {@link UserGroupService#retrieveUserGroupByStatus(String,
+ * {@link UserGroupService#retrieveUserGroupByStatus(String,
* String, de.ids_mannheim.korap.constant.UserGroupStatus)}
- *
+ *
* @throws KustvaktException
*/
-// @Test
-// public void testListUserGroupsWithAdminToken () throws KustvaktException {
-// Response response = target().path(API_VERSION).path("group")
-// .path("list").path("system-admin")
-// .queryParam("username", "dory")
-// .queryParam("token", "secret")
-// .request()
-// .get();
-//
-// assertEquals(Status.OK.getStatusCode(), response.getStatus());
-// String entity = response.readEntity(String.class);
-// JsonNode node = JsonUtils.readTree(entity);
-// assertEquals(3, node.size());
-// }
-
-
+ // @Test
+ // public void testListUserGroupsWithAdminToken () throws KustvaktException {
+ // Response response = target().path(API_VERSION).path("group")
+ // .path("list").path("system-admin")
+ // .queryParam("username", "dory")
+ // .queryParam("token", "secret")
+ // .request()
+ // .get();
+ //
+ // assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ // String entity = response.readEntity(String.class);
+ // JsonNode node = JsonUtils.readTree(entity);
+ // assertEquals(3, node.size());
+ // }
@Test
- public void testListUserGroupsUnauthorized () throws KustvaktException {
+ public void testListUserGroupsUnauthorized() throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
-
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -112,20 +87,11 @@
}
@Test
- public void testListUserGroupsWithStatus () throws KustvaktException {
+ public void testListUserGroupsWithStatus() throws KustvaktException {
Form f = new Form();
f.param("username", "dory");
f.param("status", "ACTIVE");
-
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .queryParam("username", "dory").queryParam("status", "ACTIVE")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").queryParam("username", "dory").queryParam("status", "ACTIVE").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
// System.out.println(entity);
@@ -135,35 +101,19 @@
// same as list user-groups of the admin
@Test
- public void testListWithoutUsername () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ public void testListWithoutUsername() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
- assertEquals("[]", entity);
+ assertEquals(entity, "[]");
}
@Test
- public void testListByStatusAll () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(null);
-
+ public void testListByStatusAll() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(null);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
boolean containsHiddenStatus = false;
for (int i = 0; i < node.size(); i++) {
if (node.get(i).at("/status").asText().equals("HIDDEN")) {
@@ -174,21 +124,10 @@
}
@Test
- public void testListByStatusHidden () throws
- ProcessingException, KustvaktException {
+ public void testListByStatusHidden() throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("status", "HIDDEN");
-
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .queryParam("status", "HIDDEN")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").queryParam("status", "HIDDEN").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -197,108 +136,57 @@
}
@Test
- public void testUserGroupAdmin () throws
- ProcessingException, KustvaktException {
-
+ public void testUserGroupAdmin() throws ProcessingException, KustvaktException {
String groupName = "admin-test-group";
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName)
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser,
- "password"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .put(Entity.form(new Form()));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(new Form()));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
// list user group
JsonNode node = listGroup(testUser);
assertEquals(1, node.size());
node = node.get(0);
assertEquals(groupName, node.get("name").asText());
-
testInviteMember(groupName);
testMemberRole("marlin", groupName);
testDeleteMember(groupName);
testDeleteGroup(groupName);
}
- private void testMemberRole (String memberUsername, String groupName)
- throws ProcessingException,
- KustvaktException {
-
+ private void testMemberRole(String memberUsername, String groupName) throws ProcessingException, KustvaktException {
// accept invitation
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(
- memberUsername, "pass"))
- .post(Entity.form(new Form()));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(memberUsername, "pass")).post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testAddMemberRoles(groupName, memberUsername);
testDeleteMemberRoles(groupName, memberUsername);
}
- private void testAddMemberRoles (String groupName, String memberUsername)
- throws ProcessingException,
- KustvaktException {
+ private void testAddMemberRoles(String groupName, String memberUsername) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", memberUsername);
- form.param("roleId", "1"); // USER_GROUP_ADMIN
- form.param("roleId", "2"); // USER_GROUP_MEMBER
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("role").path("add")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser,
- "password"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .post(Entity.form(form));
-
+ // USER_GROUP_ADMIN
+ form.param("roleId", "1");
+ // USER_GROUP_MEMBER
+ form.param("roleId", "2");
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("role").path("add").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = retrieveGroup(groupName).at("/members");
JsonNode member;
for (int i = 0; i < node.size(); i++) {
member = node.get(i);
if (member.at("/userId").asText().equals(memberUsername)) {
assertEquals(3, member.at("/roles").size());
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(),
- member.at("/roles/0").asText());
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(), member.at("/roles/0").asText());
break;
}
}
}
- private void testDeleteMemberRoles (String groupName, String memberUsername)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteMemberRoles(String groupName, String memberUsername) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", memberUsername);
- form.param("roleId", "1"); // USER_GROUP_ADMIN
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("role").path("delete")
- .request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser,
- "password"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .post(Entity.form(form));
-
+ // USER_GROUP_ADMIN
+ form.param("roleId", "1");
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("role").path("delete").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "password")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = retrieveGroup(groupName).at("/members");
JsonNode member;
for (int i = 0; i < node.size(); i++) {
@@ -310,92 +198,46 @@
}
}
- private JsonNode retrieveGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("admin")
- .path("group").path("@" + groupName).request()
- .header(Attributes.AUTHORIZATION,
- HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(
- sysAdminUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .post(null);
-
+ private JsonNode retrieveGroup(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testDeleteGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteGroup(String groupName) throws ProcessingException, KustvaktException {
// delete group
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check group
JsonNode node = listGroup(testUser);
assertEquals(0, node.size());
}
- private void testDeleteMember (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteMember(String groupName) throws ProcessingException, KustvaktException {
// delete marlin from group
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("~marlin")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~marlin").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check group member
JsonNode node = listGroup(testUser);
node = node.get(0);
assertEquals(3, node.get("members").size());
- assertEquals("nemo", node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.PENDING.name(),
- node.at("/members/1/status").asText());
+ assertEquals(node.at("/members/1/userId").asText(), "nemo");
+ assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
}
- private void testInviteMember (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testInviteMember(String groupName) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "marlin,nemo,darla");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(sysAdminUser, "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(sysAdminUser, "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// list group
JsonNode node = listGroup(testUser);
node = node.get(0);
assertEquals(4, node.get("members").size());
-
- assertEquals("darla", node.at("/members/3/userId").asText());
- assertEquals(GroupMemberStatus.PENDING.name(),
- node.at("/members/1/status").asText());
+ assertEquals(node.at("/members/3/userId").asText(), "darla");
+ assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
index 3b6bc5f..8742128 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserGroupControllerTest.java
@@ -1,17 +1,16 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Set;
-
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -31,7 +30,6 @@
/**
* @author margaretha
- *
*/
public class UserGroupControllerTest extends SpringJerseyTest {
@@ -39,87 +37,55 @@
private UserGroupMemberDao memberDao;
private String username = "UserGroupControllerTest";
+
private String admin = "admin";
- private JsonNode retrieveUserGroups (String username)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ private JsonNode retrieveUserGroups(String username) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
return JsonUtils.readTree(entity);
}
-
- private void deleteGroupByName (String groupName) throws KustvaktException{
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+
+ private void deleteGroupByName(String groupName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
// dory is a group admin in dory-group
@Test
- public void testListDoryGroups () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ public void testListDoryGroups() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
JsonNode group = node.get(1);
assertEquals(2, group.at("/id").asInt());
- assertEquals("dory-group", group.at("/name").asText());
- assertEquals("dory", group.at("/owner").asText());
+ assertEquals(group.at("/name").asText(), "dory-group");
+ assertEquals(group.at("/owner").asText(), "dory");
assertEquals(3, group.at("/members").size());
}
// nemo is a group member in dory-group
@Test
- public void testListNemoGroups () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("nemo", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ public void testListNemoGroups() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2, node.at("/0/id").asInt());
- assertEquals("dory-group", node.at("/0/name").asText());
- assertEquals("dory", node.at("/0/owner").asText());
+ assertEquals(node.at("/0/name").asText(), "dory-group");
+ assertEquals(node.at("/0/owner").asText(), "dory");
// group members are not allowed to see other members
assertEquals(0, node.at("/0/members").size());
}
// marlin has 2 groups
@Test
- public void testListMarlinGroups () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ public void testListMarlinGroups() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
@@ -127,556 +93,314 @@
}
@Test
- public void testListGroupGuest () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ public void testListGroupGuest() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: guest",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: guest");
}
-
@Test
- public void testCreateGroupEmptyDescription () throws
- ProcessingException, KustvaktException {
+ public void testCreateGroupEmptyDescription() throws ProcessingException, KustvaktException {
String groupName = "empty_group";
- Response response = testCreateUserGroup(groupName,"");
+ Response response = testCreateUserGroup(groupName, "");
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
deleteGroupByName(groupName);
}
-
@Test
- public void testCreateGroupMissingDescription () throws
- ProcessingException, KustvaktException {
+ public void testCreateGroupMissingDescription() throws ProcessingException, KustvaktException {
String groupName = "missing-desc-group";
-
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
deleteGroupByName(groupName);
}
-
- private Response testCreateUserGroup (String groupName, String description)
- throws ProcessingException,
- KustvaktException {
+
+ private Response testCreateUserGroup(String groupName, String description) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("description", description);
-
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .put(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(form));
return response;
}
-
- private Response testCreateGroupWithoutDescription (String groupName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .put(Entity.form(new Form()));
+ private Response testCreateGroupWithoutDescription(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").put(Entity.form(new Form()));
return response;
}
-
- @Test
- public void testCreateGroupInvalidName () throws
- ProcessingException, KustvaktException {
- String groupName = "invalid-group-name$";
+ @Test
+ public void testCreateGroupInvalidName() throws ProcessingException, KustvaktException {
+ String groupName = "invalid-group-name$";
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
-// assertEquals("User-group name must only contains letters, numbers, "
-// + "underscores, hypens and spaces", node.at("/errors/0/1").asText());
- assertEquals("invalid-group-name$", node.at("/errors/0/2").asText());
+ // assertEquals("User-group name must only contains letters, numbers, "
+ // + "underscores, hypens and spaces", node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "invalid-group-name$");
}
-
- @Test
- public void testCreateGroupNameTooShort () throws
- ProcessingException, KustvaktException {
- String groupName = "a";
+ @Test
+ public void testCreateGroupNameTooShort() throws ProcessingException, KustvaktException {
+ String groupName = "a";
Response response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("groupName must contain at least 3 characters",
- node.at("/errors/0/1").asText());
- assertEquals("groupName", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "groupName must contain at least 3 characters");
+ assertEquals(node.at("/errors/0/2").asText(), "groupName");
}
-
- @Test
- public void testUserGroup () throws
- ProcessingException, KustvaktException {
+ @Test
+ public void testUserGroup() throws ProcessingException, KustvaktException {
String groupName = "new-user-group";
- String description= "This is new-user-group.";
-
- Response response =
- testCreateUserGroup(groupName, description);
+ String description = "This is new-user-group.";
+ Response response = testCreateUserGroup(groupName, description);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
// same name
response = testCreateGroupWithoutDescription(groupName);
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
-
// list user group
JsonNode node = retrieveUserGroups(username);
assertEquals(1, node.size());
node = node.get(0);
- assertEquals("new-user-group", node.get("name").asText());
+ assertEquals(node.get("name").asText(), "new-user-group");
assertEquals(description, node.get("description").asText());
-
assertEquals(username, node.get("owner").asText());
assertEquals(1, node.get("members").size());
assertEquals(username, node.at("/members/0/userId").asText());
- assertEquals(GroupMemberStatus.ACTIVE.name(),
- node.at("/members/0/status").asText());
- assertEquals(PredefinedRole.VC_ACCESS_ADMIN.name(),
- node.at("/members/0/roles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(),
- node.at("/members/0/roles/0").asText());
-
+ assertEquals(GroupMemberStatus.ACTIVE.name(), node.at("/members/0/status").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_ADMIN.name(), node.at("/members/0/roles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_ADMIN.name(), node.at("/members/0/roles/0").asText());
testUpdateUserGroup(groupName);
testInviteMember(groupName);
-
testDeleteMemberUnauthorized(groupName);
testDeleteMember(groupName);
testDeleteGroup(groupName);
-
testSubscribeToDeletedGroup(groupName);
testUnsubscribeToDeletedGroup(groupName);
}
- private void testUpdateUserGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testUpdateUserGroup(String groupName) throws ProcessingException, KustvaktException {
String description = "Description is updated.";
Response response = testCreateUserGroup(groupName, description);
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
-
JsonNode node = retrieveUserGroups(username);
assertEquals(1, node.size());
assertEquals(description, node.get(0).get("description").asText());
}
- private void testDeleteMember (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteMember(String groupName) throws ProcessingException, KustvaktException {
// delete darla from group
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("~darla")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~darla").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
// check group member
- response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
node = node.get(0);
assertEquals(1, node.get("members").size());
}
- private void testDeleteMemberUnauthorized (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteMemberUnauthorized(String groupName) throws ProcessingException, KustvaktException {
// nemo is a group member
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("~darla")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("nemo", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("~darla").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: nemo",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: nemo");
}
// EM: same as cancel invitation
- private void testDeletePendingMember () throws
- ProcessingException, KustvaktException {
+ private void testDeletePendingMember() throws ProcessingException, KustvaktException {
// dory delete pearl
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("~pearl")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("~pearl").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check member
JsonNode node = retrieveUserGroups("pearl");
assertEquals(0, node.size());
}
@Test
- public void testDeleteDeletedMember () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("~pearl")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ public void testDeleteDeletedMember() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("~pearl").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
- node.at("/errors/0/0").asInt());
- assertEquals("pearl has already been deleted from the group dory-group",
- node.at("/errors/0/1").asText());
- assertEquals("[pearl, dory-group]", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
+ assertEquals(node.at("/errors/0/2").asText(), "[pearl, dory-group]");
}
- private void testDeleteGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testDeleteGroup(String groupName) throws ProcessingException, KustvaktException {
// delete group
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
Form f = new Form();
f.param("username", username);
f.param("status", "DELETED");
- // EM: this is so complicated because the group retrieval are not allowed
+ // EM: this is so complicated because the group retrieval are not allowed
// for delete groups
// check group
- response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- for (int j = 0; j < node.size(); j++){
+ for (int j = 0; j < node.size(); j++) {
JsonNode group = node.get(j);
// check group members
for (int i = 0; i < group.at("/0/members").size(); i++) {
- assertEquals(GroupMemberStatus.DELETED.name(),
- group.at("/0/members/" + i + "/status").asText());
+ assertEquals(GroupMemberStatus.DELETED.name(), group.at("/0/members/" + i + "/status").asText());
}
}
}
@Test
- public void testDeleteGroupUnauthorized () throws
- ProcessingException, KustvaktException {
+ public void testDeleteGroupUnauthorized() throws ProcessingException, KustvaktException {
// dory is a group admin in marlin-group
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: dory",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: dory");
}
@Test
- public void testDeleteDeletedGroup () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@deleted-group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ public void testDeleteDeletedGroup() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@deleted-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals("Group deleted-group has been deleted.",
- node.at("/errors/0/1").asText());
- assertEquals("deleted-group", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Group deleted-group has been deleted.");
+ assertEquals(node.at("/errors/0/2").asText(), "deleted-group");
}
@Test
- public void testDeleteGroupOwner () throws
- ProcessingException, KustvaktException {
+ public void testDeleteGroupOwner() throws ProcessingException, KustvaktException {
// delete marlin from marlin-group
// dory is a group admin in marlin-group
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group").path("~marlin")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("~marlin").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
- assertEquals("Operation 'delete group owner'is not allowed.",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Operation 'delete group owner'is not allowed.");
}
- private void testInviteMember (String groupName)
- throws ProcessingException,
- KustvaktException {
+ private void testInviteMember(String groupName) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "darla");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// list group
- response = target().path(API_VERSION).path("group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
node = node.get(0);
assertEquals(2, node.get("members").size());
-
- assertEquals("darla", node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.PENDING.name(),
- node.at("/members/1/status").asText());
+ assertEquals(node.at("/members/1/userId").asText(), "darla");
+ assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
- private void testInviteDeletedMember () throws
- ProcessingException, KustvaktException {
+ private void testInviteDeletedMember() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "marlin");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check member
JsonNode node = retrieveUserGroups("marlin");
assertEquals(2, node.size());
JsonNode group = node.get(1);
- assertEquals(GroupMemberStatus.PENDING.name(),
- group.at("/userMemberStatus").asText());
-
+ assertEquals(GroupMemberStatus.PENDING.name(), group.at("/userMemberStatus").asText());
}
@Test
- public void testInviteDeletedMember2 () throws
- ProcessingException, KustvaktException {
+ public void testInviteDeletedMember2() throws ProcessingException, KustvaktException {
// pearl has status deleted in dory-group
Form form = new Form();
form.param("members", "pearl");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check member
JsonNode node = retrieveUserGroups("pearl");
assertEquals(1, node.size());
JsonNode group = node.get(0);
- assertEquals(GroupMemberStatus.PENDING.name(),
- group.at("/userMemberStatus").asText());
-
+ assertEquals(GroupMemberStatus.PENDING.name(), group.at("/userMemberStatus").asText());
testDeletePendingMember();
}
@Test
- public void testInvitePendingMember () throws
- ProcessingException, KustvaktException {
+ public void testInvitePendingMember() throws ProcessingException, KustvaktException {
// marlin has status PENDING in dory-group
Form form = new Form();
form.param("members", "marlin");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(form));
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_EXISTS,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Username marlin with status PENDING exists in the user-group "
- + "dory-group",
- node.at("/errors/0/1").asText());
- assertEquals("[marlin, PENDING, dory-group]",
- node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_EXISTS, node.at("/errors/0/0").asInt());
+ assertEquals("Username marlin with status PENDING exists in the user-group " + "dory-group", node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[marlin, PENDING, dory-group]");
}
@Test
- public void testInviteActiveMember () throws
- ProcessingException, KustvaktException {
+ public void testInviteActiveMember() throws ProcessingException, KustvaktException {
// nemo has status active in dory-group
Form form = new Form();
form.param("members", "nemo");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.GROUP_MEMBER_EXISTS,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "Username nemo with status ACTIVE exists in the user-group "
- + "dory-group",
- node.at("/errors/0/1").asText());
- assertEquals("[nemo, ACTIVE, dory-group]",
- node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_EXISTS, node.at("/errors/0/0").asInt());
+ assertEquals("Username nemo with status ACTIVE exists in the user-group " + "dory-group", node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/2").asText(), "[nemo, ACTIVE, dory-group]");
}
@Test
- public void testInviteMemberToDeletedGroup ()
- throws ProcessingException,
- KustvaktException {
+ public void testInviteMemberToDeletedGroup() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", "nemo");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@deleted-group").path("invite")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@deleted-group").path("invite").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(form));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals("Group deleted-group has been deleted.",
- node.at("/errors/0/1").asText());
- assertEquals("deleted-group", node.at("/errors/0/2").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Group deleted-group has been deleted.");
+ assertEquals(node.at("/errors/0/2").asText(), "deleted-group");
}
// marlin has GroupMemberStatus.PENDING in dory-group
@Test
- public void testSubscribePendingMember () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .post(Entity.form(new Form()));
-
+ public void testSubscribePendingMember() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// retrieve marlin group
JsonNode node = retrieveUserGroups("marlin");
// System.out.println(node);
assertEquals(2, node.size());
-
JsonNode group = node.get(1);
assertEquals(2, group.at("/id").asInt());
- assertEquals("dory-group", group.at("/name").asText());
- assertEquals("dory", group.at("/owner").asText());
+ assertEquals(group.at("/name").asText(), "dory-group");
+ assertEquals(group.at("/owner").asText(), "dory");
// group members are not allowed to see other members
assertEquals(0, group.at("/members").size());
- assertEquals(GroupMemberStatus.ACTIVE.name(),
- group.at("/userMemberStatus").asText());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
- group.at("/userRoles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
- group.at("/userRoles/0").asText());
-
+ assertEquals(GroupMemberStatus.ACTIVE.name(), group.at("/userMemberStatus").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), group.at("/userRoles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), group.at("/userRoles/0").asText());
// unsubscribe marlin from dory-group
testUnsubscribeActiveMember("dory-group");
checkGroupMemberRole("dory-group", "marlin");
-
// invite marlin to dory-group to set back the
// GroupMemberStatus.PENDING
testInviteDeletedMember();
@@ -684,125 +408,62 @@
// pearl has GroupMemberStatus.DELETED in dory-group
@Test
- public void testSubscribeDeletedMember () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("pearl", "pass"))
- .post(Entity.form(new Form()));
+ public void testSubscribeDeletedMember() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
- node.at("/errors/0/0").asInt());
- assertEquals("pearl has already been deleted from the group dory-group",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
}
@Test
public void testSubscribeMissingGroupName() throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("bruce", "pass"))
- .post(Entity.form(new Form()));
- assertEquals(Status.NOT_FOUND.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).post(Entity.form(new Form()));
+ assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
- public void testSubscribeNonExistentMember () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("bruce", "pass"))
- .post(Entity.form(new Form()));
+ public void testSubscribeNonExistentMember() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("bruce is not found in the group",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "bruce is not found in the group");
}
@Test
- public void testSubscribeToNonExistentGroup () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@non-existent").path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("pearl", "pass"))
- .post(Entity.form(new Form()));
+ public void testSubscribeToNonExistentGroup() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@non-existent").path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).post(Entity.form(new Form()));
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("Group non-existent is not found",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Group non-existent is not found");
}
- private void testSubscribeToDeletedGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("subscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("nemo", "pass"))
- .post(Entity.form(new Form()));
-
+ private void testSubscribeToDeletedGroup(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).post(Entity.form(new Form()));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals("Group new-user-group has been deleted.",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Group new-user-group has been deleted.");
}
- private void testUnsubscribeActiveMember (String groupName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .delete();
-
+ private void testUnsubscribeActiveMember(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = retrieveUserGroups("marlin");
assertEquals(1, node.size());
}
- private void checkGroupMemberRole (String groupName, String deletedMemberName)
- throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .post(null);
+ private void checkGroupMemberRole(String groupName, String deletedMemberName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).post(null);
String entity = response.readEntity(String.class);
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity).at("/members");
JsonNode member;
for (int i = 0; i < node.size(); i++) {
@@ -815,217 +476,112 @@
}
@Test
- public void testUnsubscribeDeletedMember ()
- throws ProcessingException,
- KustvaktException {
+ public void testUnsubscribeDeletedMember() throws ProcessingException, KustvaktException {
// pearl unsubscribes from dory-group
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("pearl", "pass"))
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).delete();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.GROUP_MEMBER_DELETED,
- node.at("/errors/0/0").asInt());
- assertEquals("pearl has already been deleted from the group dory-group",
- node.at("/errors/0/1").asText());
- assertEquals("[pearl, dory-group]", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_DELETED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "pearl has already been deleted from the group dory-group");
+ assertEquals(node.at("/errors/0/2").asText(), "[pearl, dory-group]");
}
@Test
- public void testUnsubscribePendingMember ()
- throws ProcessingException,
- KustvaktException {
-
+ public void testUnsubscribePendingMember() throws ProcessingException, KustvaktException {
JsonNode node = retrieveUserGroups("marlin");
assertEquals(2, node.size());
-
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .delete();
-
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
node = retrieveUserGroups("marlin");
assertEquals(1, node.size());
-
// invite marlin to dory-group to set back the
// GroupMemberStatus.PENDING
testInviteDeletedMember();
}
@Test
- public void testUnsubscribeMissingGroupName () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .delete();
-
+ public void testUnsubscribeMissingGroupName() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
}
@Test
- public void testUnsubscribeNonExistentMember () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@dory-group").path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("bruce", "pass"))
- .delete();
-
+ public void testUnsubscribeNonExistentMember() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@dory-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("bruce", "pass")).delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("bruce is not found in the group",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.GROUP_MEMBER_NOT_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "bruce is not found in the group");
}
@Test
- public void testUnsubscribeToNonExistentGroup () throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@tralala-group").path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("pearl", "pass"))
- .delete();
-
+ public void testUnsubscribeToNonExistentGroup() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@tralala-group").path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).delete();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("Group tralala-group is not found",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Group tralala-group is not found");
}
- private void testUnsubscribeToDeletedGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("group")
- .path("@"+groupName).path("unsubscribe")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("nemo", "pass"))
- .delete();
-
+ private void testUnsubscribeToDeletedGroup(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("unsubscribe").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.GROUP_DELETED, node.at("/errors/0/0").asInt());
- assertEquals("Group new-user-group has been deleted.",
- node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "Group new-user-group has been deleted.");
}
@Test
- public void testAddSameMemberRole () throws
- ProcessingException, KustvaktException {
+ public void testAddSameMemberRole() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group").path("role").path("add")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("add").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
assertEquals(2, roles.size());
}
@Test
- public void testDeleteAddMemberRole () throws
- ProcessingException, KustvaktException {
+ public void testDeleteAddMemberRole() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group").path("role").path("delete")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("delete").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
assertEquals(1, roles.size());
-
testAddSameMemberRole();
}
@Test
- public void testEditMemberRoleEmpty () throws
- ProcessingException, KustvaktException {
+ public void testEditMemberRoleEmpty() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group").path("role").path("edit")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("edit").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
assertEquals(0, roles.size());
-
testEditMemberRole();
}
- private void testEditMemberRole ()
- throws ProcessingException,
- KustvaktException {
+ private void testEditMemberRole() throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("memberUsername", "dory");
form.param("roleId", "1");
form.param("roleId", "3");
-
- Response response = target().path(API_VERSION).path("group")
- .path("@marlin-group").path("role").path("edit")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@marlin-group").path("role").path("edit").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
UserGroupMember member = memberDao.retrieveMemberById("dory", 1);
Set<Role> roles = member.getRoles();
assertEquals(2, roles.size());
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
index 40fa517..7aac962 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/UserSettingControllerTest.java
@@ -1,17 +1,16 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.HashMap;
import java.util.Map;
-
import javax.ws.rs.client.Entity;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -24,267 +23,151 @@
/**
* @author margaretha
- *
*/
public class UserSettingControllerTest extends SpringJerseyTest {
private String username = "UserSetting_Test";
+
private String username2 = "UserSetting.Test2";
- public Response sendPutRequest (String username,
- Map<String, Object> map) throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .put(Entity.json(map));
-
+ public Response sendPutRequest(String username, Map<String, Object> map) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(map));
return response;
}
@Test
- public void testCreateSettingWithJson () throws KustvaktException {
- String json =
- "{\"pos-foundry\":\"opennlp\",\"metadata\":[\"author\", \"title\","
- + "\"textSigle\", \"availability\"],\"resultPerPage\":25}";
-
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .put(Entity.json(json));
-
+ public void testCreateSettingWithJson() throws KustvaktException {
+ String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":[\"author\", \"title\"," + "\"textSigle\", \"availability\"],\"resultPerPage\":25}";
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
int numOfResult = 25;
- String metadata =
- "[\"author\",\"title\",\"textSigle\"," + "\"availability\"]";
-
+ String metadata = "[\"author\",\"title\",\"textSigle\"," + "\"availability\"]";
testRetrieveSettings(username, "opennlp", numOfResult, metadata, true);
-
testDeleteKeyNotExist(username);
testDeleteKey(username, numOfResult, metadata, true);
testDeleteSetting(username);
}
@Test
- public void testCreateSettingWithMap () throws KustvaktException {
-
+ public void testCreateSettingWithMap() throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("pos-foundry", "opennlp");
map.put("resultPerPage", 25);
map.put("metadata", "author title textSigle availability");
-
Response response = sendPutRequest(username2, map);
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
- testRetrieveSettings(username2, "opennlp", 25,
- "author title textSigle availability", false);
-
+ testRetrieveSettings(username2, "opennlp", 25, "author title textSigle availability", false);
testUpdateSetting(username2);
testputRequestInvalidKey();
}
@Test
- public void testputRequestInvalidKey () throws KustvaktException {
+ public void testputRequestInvalidKey() throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("key/", "invalidKey");
-
Response response = sendPutRequest(username2, map);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- assertEquals("key/", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/2").asText(), "key/");
}
@Test
- public void testPutDifferentUsername () throws KustvaktException {
- String json =
- "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title "
- + "textSigle availability\",\"resultPerPage\":25}";
-
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username2, "pass"))
- .put(Entity.json(json));
-
+ public void testPutDifferentUsername() throws KustvaktException {
+ String json = "{\"pos-foundry\":\"opennlp\",\"metadata\":\"author title " + "textSigle availability\",\"resultPerPage\":25}";
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
}
@Test
- public void testGetDifferentUsername () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username2, "pass"))
- .get();
-
+ public void testGetDifferentUsername() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
}
@Test
- public void testGetSettingNotExist () throws KustvaktException {
+ public void testGetSettingNotExist() throws KustvaktException {
String username = "tralala";
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .get();
-
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals(
- "No default setting for username: " + username + " is found",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals("No default setting for username: " + username + " is found", node.at("/errors/0/1").asText());
assertEquals(username, node.at("/errors/0/2").asText());
}
@Test
- public void testDeleteSettingNotExist () throws KustvaktException {
+ public void testDeleteSettingNotExist() throws KustvaktException {
String username = "tralala";
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
@Test
- public void testDeleteKeyDifferentUsername () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting").path("pos-foundry")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username2, "pass"))
- .delete();
-
+ public void testDeleteKeyDifferentUsername() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").path("pos-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username2, "pass")).delete();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
}
- private void testDeleteSetting (String username) throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ private void testDeleteSetting(String username) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
- response = target().path(API_VERSION).path("~" + username)
- .path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
assertEquals(username, node.at("/errors/0/2").asText());
}
// EM: deleting a non-existing key does not throw an error,
// because
// the purpose of the request has been achieved.
- private void testDeleteKeyNotExist (String username)
- throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting").path("lemma-foundry")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ private void testDeleteKeyNotExist(String username) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").path("lemma-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void testDeleteKey (String username, int numOfResult,
- String metadata, boolean isMetadataArray) throws KustvaktException {
-
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting").path("pos-foundry")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ private void testDeleteKey(String username, int numOfResult, String metadata, boolean isMetadataArray) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").path("pos-foundry").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
- testRetrieveSettings(username, null, numOfResult, metadata,
- isMetadataArray);
+ testRetrieveSettings(username, null, numOfResult, metadata, isMetadataArray);
}
- private void testUpdateSetting (String username) throws KustvaktException {
+ private void testUpdateSetting(String username) throws KustvaktException {
Map<String, Object> map = new HashMap<>();
map.put("pos-foundry", "malt");
map.put("resultPerPage", 15);
map.put("metadata", "author title");
-
Response response = sendPutRequest(username, map);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
testRetrieveSettings(username, "malt", 15, "author title", false);
}
- private void testRetrieveSettings (String username, String posFoundry,
- int numOfResult, String metadata, boolean isMetadataArray)
- throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("~" + username).path("setting")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
+ private void testRetrieveSettings(String username, String posFoundry, int numOfResult, String metadata, boolean isMetadataArray) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("~" + username).path("setting").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
if (posFoundry == null) {
assertTrue(node.at("/pos-foundry").isMissingNode());
- }
- else {
+ } else {
assertEquals(posFoundry, node.at("/pos-foundry").asText());
}
assertEquals(numOfResult, node.at("/resultPerPage").asInt());
-
if (isMetadataArray) {
assertEquals(metadata, node.at("/metadata").toString());
- }
- else {
+ } else {
assertEquals(metadata, node.at("/metadata").asText());
}
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
index fe2c1df..9cce1a0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VCReferenceTest.java
@@ -1,15 +1,14 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
@@ -35,64 +34,51 @@
@Autowired
private NamedVCLoader vcLoader;
+
@Autowired
private QueryDao dao;
/**
* VC data exists, but it has not been cached, so it is not found
* in the DB.
- *
+ *
* @throws KustvaktException
*/
@Test
- public void testRefVcNotPrecached () throws KustvaktException {
+ public void testRefVcNotPrecached() throws KustvaktException {
JsonNode node = testSearchWithRef_VC1();
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("Virtual corpus system/named-vc1 is not found.",
- node.at("/errors/0/1").asText());
- assertEquals("system/named-vc1", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Virtual corpus system/named-vc1 is not found.");
+ assertEquals(node.at("/errors/0/2").asText(), "system/named-vc1");
}
-
+
@Test
- public void testRefVcPrecached ()
- throws KustvaktException, IOException, QueryException {
+ public void testRefVcPrecached() throws KustvaktException, IOException, QueryException {
int numOfMatches = testSearchWithoutRef_VC1();
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
assertTrue(VirtualCorpusCache.contains("named-vc1"));
JsonNode node = testSearchWithRef_VC1();
- assertEquals(numOfMatches,node.at("/matches").size());
-
+ assertEquals(numOfMatches, node.at("/matches").size());
testStatisticsWithRef();
-
numOfMatches = testSearchWithoutRef_VC2();
vcLoader.loadVCToCache("named-vc2", "/vc/named-vc2.jsonld");
assertTrue(VirtualCorpusCache.contains("named-vc2"));
node = testSearchWithRef_VC2();
- assertEquals(numOfMatches,node.at("/matches").size());
-
+ assertEquals(numOfMatches, node.at("/matches").size());
VirtualCorpusCache.delete("named-vc2");
assertFalse(VirtualCorpusCache.contains("named-vc2"));
-
QueryDO vc = dao.retrieveQueryByName("named-vc1", "system");
dao.deleteQuery(vc);
vc = dao.retrieveQueryByName("named-vc1", "system");
assertNull(vc);
-
vc = dao.retrieveQueryByName("named-vc2", "system");
dao.deleteQuery(vc);
vc = dao.retrieveQueryByName("named-vc2", "system");
assertNull(vc);
}
-
- private int testSearchWithoutRef_VC1 () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq",
- "textSigle=\"GOE/AGF/00000\" | textSigle=\"GOE/AGA/01784\"")
- .request()
- .get();
+ private int testSearchWithoutRef_VC1() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "textSigle=\"GOE/AGF/00000\" | textSigle=\"GOE/AGA/01784\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
int size = node.at("/matches").size();
@@ -100,14 +86,8 @@
return size;
}
- private int testSearchWithoutRef_VC2 () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq",
- "textSigle!=\"GOE/AGI/04846\" & textSigle!=\"GOE/AGA/01784\"")
- .request()
- .get();
-
+ private int testSearchWithoutRef_VC2() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "textSigle!=\"GOE/AGI/04846\" & textSigle!=\"GOE/AGA/01784\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
int size = node.at("/matches").size();
@@ -115,133 +95,81 @@
return size;
}
- private JsonNode testSearchWithRef_VC1 () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"system/named-vc1\"")
- .request()
- .get();
-
+ private JsonNode testSearchWithRef_VC1() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"system/named-vc1\"").request().get();
String ent = response.readEntity(String.class);
return JsonUtils.readTree(ent);
}
- private JsonNode testSearchWithRef_VC2 () throws KustvaktException {
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo named-vc2")
- .request()
- .get();
-
+ private JsonNode testSearchWithRef_VC2() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo named-vc2").request().get();
String ent = response.readEntity(String.class);
return JsonUtils.readTree(ent);
}
@Test
- public void testStatisticsWithRef () throws KustvaktException {
+ public void testStatisticsWithRef() throws KustvaktException {
String corpusQuery = "availability = /CC-BY.*/ & referTo named-vc1";
- Response response = target().path(API_VERSION)
- .path("statistics").queryParam("corpusQuery", corpusQuery)
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", corpusQuery).request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertEquals(2, node.at("/documents").asInt());
-
VirtualCorpusCache.delete("named-vc1");
assertFalse(VirtualCorpusCache.contains("named-vc1"));
}
@Test
- public void testRefVcNotExist () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"username/vc1\"")
- .request()
- .get();
-
+ public void testRefVcNotExist() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"username/vc1\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("username/vc1", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/2").asText(), "username/vc1");
}
@Test
public void testRefNotAuthorized() throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"dory/dory-vc\"")
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"dory/dory-vc\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("guest", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/2").asText(), "guest");
}
-
- @Test
- public void testSearchWithRefPublishedVcGuest () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"marlin/published-vc\"")
- .request()
- .get();
+ @Test
+ public void testSearchWithRefPublishedVcGuest() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"marlin/published-vc\"").request().get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
-
- assertEquals("CC-BY.*", node.at("/collection/operands/0/value").asText());
- assertEquals("koral:doc", node.at("/collection/operands/1/@type").asText());
- assertEquals("GOE", node.at("/collection/operands/1/value").asText());
- assertEquals("corpusSigle", node.at("/collection/operands/1/key").asText());
-
+ assertEquals(node.at("/collection/operands/0/value").asText(), "CC-BY.*");
+ assertEquals(node.at("/collection/operands/1/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "GOE");
+ assertEquals(node.at("/collection/operands/1/key").asText(), "corpusSigle");
node = node.at("/collection/operands/1/rewrites");
assertEquals(3, node.size());
- assertEquals("operation:deletion", node.at("/0/operation").asText());
- assertEquals("@type(koral:docGroupRef)", node.at("/0/scope").asText());
- assertEquals("operation:deletion", node.at("/1/operation").asText());
- assertEquals("ref(marlin/published-vc)", node.at("/1/scope").asText());
- assertEquals("operation:insertion", node.at("/2/operation").asText());
+ assertEquals(node.at("/0/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/0/scope").asText(), "@type(koral:docGroupRef)");
+ assertEquals(node.at("/1/operation").asText(), "operation:deletion");
+ assertEquals(node.at("/1/scope").asText(), "ref(marlin/published-vc)");
+ assertEquals(node.at("/2/operation").asText(), "operation:insertion");
}
-
- @Test
- public void testSearchWithRefPublishedVc () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq", "referTo \"marlin/published-vc\"")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("squirt", "pass"))
- .get();
+ @Test
+ public void testSearchWithRefPublishedVc() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"marlin/published-vc\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("squirt", "pass")).get();
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertTrue(node.at("/matches").size() > 0);
-
Form f = new Form();
f.param("status", "HIDDEN");
-
// check dory in the hidden group of the vc
- response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
assertEquals(3, node.at("/0/id").asInt());
-
String members = node.at("/0/members").toString();
assertTrue(members.contains("\"userId\":\"squirt\""));
- }
+ }
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
index 1fb98b8..f86b01a 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusAccessTest.java
@@ -1,16 +1,14 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.http.HttpStatus;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.ResourceType;
@@ -19,15 +17,14 @@
import de.ids_mannheim.korap.utils.JsonUtils;
public class VirtualCorpusAccessTest extends VirtualCorpusTestBase {
+
private String testUser = "VirtualCorpusAccessTest";
@Test
- public void testlistAccessByNonVCAAdmin () throws KustvaktException {
+ public void testlistAccessByNonVCAAdmin() throws KustvaktException {
JsonNode node = listAccessByGroup("nemo", "dory-group");
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: nemo",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: nemo");
}
// @Test
@@ -50,140 +47,99 @@
// node.at("/errors/0/0").asInt());
// assertEquals("vcId", node.at("/errors/0/1").asText());
// }
-
@Test
- public void testlistAccessByGroup () throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access")
- .queryParam("groupName", "dory-group").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .get();
+ public void testlistAccessByGroup() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access").queryParam("groupName", "dory-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).get();
String entity = response.readEntity(String.class);
// System.out.println(entity);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(1, node.at("/0/accessId").asInt());
assertEquals(2, node.at("/0/queryId").asInt());
- assertEquals("group-vc", node.at("/0/queryName").asText());
+ assertEquals(node.at("/0/queryName").asText(), "group-vc");
assertEquals(2, node.at("/0/userGroupId").asInt());
-
- assertEquals("dory-group", node.at("/0/userGroupName").asText());
+ assertEquals(node.at("/0/userGroupName").asText(), "dory-group");
}
-
- @Test
- public void testDeleteSharedVC () throws KustvaktException {
- String json =
- "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
- String vcName = "new_project_vc";
-
- String username = "dory";
- String authHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass");
+ @Test
+ public void testDeleteSharedVC() throws KustvaktException {
+ String json = "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ String vcName = "new_project_vc";
+ String username = "dory";
+ String authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass");
createVC(authHeader, username, vcName, json);
-
String groupName = "dory-group";
testShareVCByCreator(username, vcName, groupName);
JsonNode node = listAccessByGroup(username, groupName);
assertEquals(2, node.size());
-
// delete project VC
deleteVC(vcName, username, username);
-
node = listAccessByGroup(username, groupName);
assertEquals(1, node.size());
}
@Test
- public void testCreateDeleteAccess ()
- throws ProcessingException, KustvaktException {
-
+ public void testCreateDeleteAccess() throws ProcessingException, KustvaktException {
String vcName = "marlin-vc";
String groupName = "marlin-group";
-
// check the vc type
JsonNode node = retrieveVCInfo("marlin", "marlin", vcName);
assertEquals(vcName, node.at("/name").asText());
- assertEquals("private", node.at("/type").asText());
-
+ assertEquals(node.at("/type").asText(), "private");
// share vc to group
Response response = testShareVCByCreator("marlin", vcName, groupName);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// check the vc type
node = retrieveVCInfo("marlin", "marlin", vcName);
- assertEquals("project", node.at("/type").asText());
-
+ assertEquals(node.at("/type").asText(), "project");
// list vc access by marlin
node = listAccessByGroup("marlin", groupName);
assertEquals(2, node.size());
-
// get access id
node = node.get(1);
assertEquals(5, node.at("/queryId").asInt());
assertEquals(vcName, node.at("/queryName").asText());
assertEquals(1, node.at("/userGroupId").asInt());
assertEquals(groupName, node.at("/userGroupName").asText());
-
String accessId = node.at("/accessId").asText();
-
testShareVC_nonUniqueAccess("marlin", vcName, groupName);
-
// delete unauthorized
response = testDeleteAccess(testUser, accessId);
testResponseUnauthorized(response, testUser);
-
// delete access by vc-admin
// dory is a vc-admin in marlin group
response = testDeleteAccess("dory", accessId);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// list vc access by dory
node = listAccessByGroup("dory", groupName);
assertEquals(1, node.size());
-
// edit VC back to private
String json = "{\"type\": \"" + ResourceType.PRIVATE + "\"}";
editVC("marlin", "marlin", vcName, json);
node = retrieveVCInfo("marlin", "marlin", vcName);
- assertEquals(ResourceType.PRIVATE.displayName(),
- node.at("/type").asText());
+ assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
}
- private void testShareVC_nonUniqueAccess (String vcCreator, String vcName,
- String groupName) throws ProcessingException, KustvaktException {
+ private void testShareVC_nonUniqueAccess(String vcCreator, String vcName, String groupName) throws ProcessingException, KustvaktException {
Response response = testShareVCByCreator(vcCreator, vcName, groupName);
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_BAD_REQUEST, response.getStatus());
- assertEquals(StatusCodes.DB_INSERT_FAILED,
- node.at("/errors/0/0").asInt());
-
+ assertEquals(StatusCodes.DB_INSERT_FAILED, node.at("/errors/0/0").asInt());
// EM: message differs depending on the database used
// for testing. The message below is from sqlite.
// assertTrue(node.at("/errors/0/1").asText()
// .startsWith("[SQLITE_CONSTRAINT_UNIQUE]"));
}
- private Response testDeleteAccess (String username, String accessId)
- throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("access")
- .path(accessId).request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .delete();
-
+ private Response testDeleteAccess(String username, String accessId) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access").path(accessId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).delete();
return response;
}
-
@Test
- public void testDeleteNonExistingAccess ()
- throws ProcessingException, KustvaktException {
+ public void testDeleteNonExistingAccess() throws ProcessingException, KustvaktException {
Response response = testDeleteAccess("dory", "100");
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
index 277b5ab..8df65a1 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusClientTest.java
@@ -1,14 +1,12 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.utils.JsonUtils;
@@ -18,75 +16,53 @@
private String username = "VirtualCorpusClientTest";
@Test
- public void testVC_withClient () throws KustvaktException {
+ public void testVC_withClient() throws KustvaktException {
// create client
Response response = registerConfidentialClient(username);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
String clientId = node.at("/client_id").asText();
String clientSecret = node.at("/client_secret").asText();
-
// obtain authorization
- String userAuthHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "password");
- response = requestAuthorizationCode("code", clientId, clientRedirectUri,
- "create_vc vc_info delete_vc edit_vc", "myState",
- userAuthHeader);
+ String userAuthHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "password");
+ response = requestAuthorizationCode("code", clientId, clientRedirectUri, "create_vc vc_info delete_vc edit_vc", "myState", userAuthHeader);
String code = parseAuthorizationCode(response);
-
- response = requestTokenWithAuthorizationCodeAndForm(clientId,
- clientSecret, code, clientRedirectUri);
+ response = requestTokenWithAuthorizationCodeAndForm(clientId, clientSecret, code, clientRedirectUri);
node = JsonUtils.readTree(response.readEntity(String.class));
String accessToken = node.at("/access_token").asText();
-
String accessTokenHeader = "Bearer " + accessToken;
-
// create VC 1
String vcName = "vc-client1";
- String vcJson =
- "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ String vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
createVC(accessTokenHeader, username, vcName, vcJson);
-
// create VC 2
vcName = "vc-client2";
- vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate until 1820\"}";
+ vcJson = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate until 1820\"}";
createVC(accessTokenHeader, username, vcName, vcJson);
-
// edit VC
String description = "vc created from client";
- vcJson = "{\"description\": \""+description+"\"}";
+ vcJson = "{\"description\": \"" + description + "\"}";
editVC(username, username, vcName, vcJson);
-
// retrieve vc info
node = retrieveVCInfo(username, username, vcName);
assertEquals(description, node.at("/description").asText());
-
// list vc
node = listVCWithAuthHeader(accessTokenHeader);
assertEquals(3, node.size());
-
// delete vc
deleteVC(vcName, username, username);
-
// list vc
node = listVCWithAuthHeader(accessTokenHeader);
assertEquals(2, node.size());
-
// delete client
deregisterClient(username, clientId);
-
testSearchWithRevokedAccessToken(accessToken);
-
// obtain authorization from another client
- response = requestTokenWithPassword(superClientId,
- this.clientSecret, username, "pass");
+ response = requestTokenWithPassword(superClientId, this.clientSecret, username, "pass");
node = JsonUtils.readTree(response.readEntity(String.class));
accessToken = node.at("/access_token").asText();
-
// checking vc should still be available after client deregistration
- node = listVCWithAuthHeader("Bearer "+accessToken);
+ node = listVCWithAuthHeader("Bearer " + accessToken);
assertEquals(2, node.size());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
index 6063f0c..807d649 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerAdminTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
@@ -10,11 +10,9 @@
import javax.ws.rs.core.Response.Status;
import org.apache.http.entity.ContentType;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.ResourceType;
@@ -23,248 +21,139 @@
/**
* @author margaretha
- *
*/
public class VirtualCorpusControllerAdminTest extends VirtualCorpusTestBase {
private String admin = "admin";
+
private String testUser = "VirtualCorpusControllerAdminTest";
- private JsonNode testAdminListVC (String username)
- throws ProcessingException,
- KustvaktException {
+ private JsonNode testAdminListVC(String username) throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("createdBy", username);
-
- Response response = target().path(API_VERSION).path("admin")
- .path("vc").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("vc").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
- private JsonNode testAdminListVC_UsingAdminToken (String username, ResourceType type)
- throws ProcessingException, KustvaktException {
+ private JsonNode testAdminListVC_UsingAdminToken(String username, ResourceType type) throws ProcessingException, KustvaktException {
Form f = new Form();
f.param("createdBy", username);
f.param("type", type.toString());
f.param("token", "secret");
-
- Response response = target().path(API_VERSION).path("admin").path("vc")
- .path("list").request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("vc").path("list").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
@Test
- public void testCreateSystemVC () throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~system").path("new-system-vc")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ public void testCreateSystemVC() throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~system").path("new-system-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
- JsonNode node = testAdminListVC_UsingAdminToken("system",ResourceType.SYSTEM);
+ JsonNode node = testAdminListVC_UsingAdminToken("system", ResourceType.SYSTEM);
assertEquals(2, node.size());
-
testDeleteSystemVC(admin, "new-system-vc");
}
- private void testDeleteSystemVC (String vcCreator, String vcName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~system").path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .delete();
-
+ private void testDeleteSystemVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~system").path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
- JsonNode node = testAdminListVC_UsingAdminToken("system",ResourceType.SYSTEM);
+ JsonNode node = testAdminListVC_UsingAdminToken("system", ResourceType.SYSTEM);
assertEquals(1, node.size());
}
@Test
- public void testCreatePrivateVC () throws
- ProcessingException, KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
-
+ public void testCreatePrivateVC() throws ProcessingException, KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new-vc";
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
JsonNode node = testAdminListVC(testUser);
assertEquals(1, node.size());
-
testEditPrivateVC(testUser, vcName);
testDeletePrivateVC(testUser, vcName);
}
-
- private void testEditPrivateVC (String vcCreator, String vcName)
- throws ProcessingException,
- KustvaktException {
-
+ private void testEditPrivateVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
String json = "{\"description\": \"edited vc\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+vcCreator).path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.NO_CONTENT.getStatusCode(), response.getStatus());
-
JsonNode node = testAdminListVC(testUser);
- assertEquals("edited vc", node.at("/0/description").asText());
+ assertEquals(node.at("/0/description").asText(), "edited vc");
}
- private void testDeletePrivateVC (String vcCreator, String vcName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+vcCreator).path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .delete();
-
+ private void testDeletePrivateVC(String vcCreator, String vcName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = testAdminListVC(vcCreator);
assertEquals(0, node.size());
}
-// @Deprecated
-// private String testlistAccessByVC (String groupName) throws KustvaktException {
-// Response response = target().path(API_VERSION).path("vc")
-// .path("access")
-// .queryParam("groupName", groupName)
-// .request()
-// .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
-// .createBasicAuthorizationHeaderValue(admin, "pass"))
-// .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
-// .get();
-//
-// String entity = response.readEntity(String.class);
-// JsonNode node = JsonUtils.readTree(entity);
-// assertEquals(1, node.size());
-// node = node.get(0);
-//
-// assertEquals(admin, node.at("/createdBy").asText());
-// assertEquals(5, node.at("/vcId").asInt());
-// assertEquals("marlin-vc", node.at("/vcName").asText());
-// assertEquals(1, node.at("/userGroupId").asInt());
-// assertEquals("marlin group", node.at("/userGroupName").asText());
-//
-// return node.at("/accessId").asText();
-// }
-
- private JsonNode testlistAccessByGroup (String groupName)
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("access")
- .queryParam("groupName", groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .get();
+ // @Deprecated
+ // private String testlistAccessByVC (String groupName) throws KustvaktException {
+ // Response response = target().path(API_VERSION).path("vc")
+ // .path("access")
+ // .queryParam("groupName", groupName)
+ // .request()
+ // .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
+ // .createBasicAuthorizationHeaderValue(admin, "pass"))
+ // .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
+ // .get();
+ //
+ // String entity = response.readEntity(String.class);
+ // JsonNode node = JsonUtils.readTree(entity);
+ // assertEquals(1, node.size());
+ // node = node.get(0);
+ //
+ // assertEquals(admin, node.at("/createdBy").asText());
+ // assertEquals(5, node.at("/vcId").asInt());
+ // assertEquals("marlin-vc", node.at("/vcName").asText());
+ // assertEquals(1, node.at("/userGroupId").asInt());
+ // assertEquals("marlin group", node.at("/userGroupName").asText());
+ //
+ // return node.at("/accessId").asText();
+ // }
+ private JsonNode testlistAccessByGroup(String groupName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access").queryParam("groupName", groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.size());
- return node.get(node.size()-1);
+ return node.get(node.size() - 1);
}
@Test
- public void testVCSharing () throws
- ProcessingException, KustvaktException {
+ public void testVCSharing() throws ProcessingException, KustvaktException {
String vcCreator = "marlin";
String vcName = "marlin-vc";
String groupName = "marlin-group";
-
- JsonNode node2 = testAdminListVC_UsingAdminToken(vcCreator,ResourceType.PROJECT);
+ JsonNode node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
assertEquals(0, node2.size());
-
testCreateVCAccess(vcCreator, vcName, groupName);
JsonNode node = testlistAccessByGroup(groupName);
-
String accessId = node.at("/accessId").asText();
testDeleteVCAccess(accessId);
-
- node2 = testAdminListVC_UsingAdminToken(vcCreator,ResourceType.PROJECT);
+ node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
assertEquals(1, node2.size());
-
String json = "{\"type\": \"" + ResourceType.PRIVATE + "\"}";
editVC(admin, vcCreator, vcName, json);
node = retrieveVCInfo(admin, vcCreator, vcName);
- assertEquals(ResourceType.PRIVATE.displayName(),
- node.at("/type").asText());
-
- node2 = testAdminListVC_UsingAdminToken(vcCreator,ResourceType.PROJECT);
+ assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
+ node2 = testAdminListVC_UsingAdminToken(vcCreator, ResourceType.PROJECT);
assertEquals(0, node2.size());
}
- private void testCreateVCAccess (String vcCreator, String vcName,
- String groupName) throws
- ProcessingException, KustvaktException {
+ private void testCreateVCAccess(String vcCreator, String vcName, String groupName) throws ProcessingException, KustvaktException {
Response response;
// share VC
- response = target().path(API_VERSION).path("vc").path("~"+vcCreator)
- .path(vcName).path("share").path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .post(Entity.form(new Form()));
-
+ response = target().path(API_VERSION).path("vc").path("~" + vcCreator).path(vcName).path("share").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
}
- private void testDeleteVCAccess (String accessId)
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("vc")
- .path("access").path(accessId)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .delete();
-
+ private void testDeleteVCAccess(String accessId) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("access").path(accessId).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).delete();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
index 47e80ec..a30a810 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusControllerTest.java
@@ -1,24 +1,21 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
-
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.http.entity.ContentType;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.AuthenticationScheme;
@@ -29,133 +26,84 @@
/**
* @author margaretha
- *
*/
public class VirtualCorpusControllerTest extends VirtualCorpusTestBase {
private String testUser = "vcControllerTest";
private String authHeader;
-
- public VirtualCorpusControllerTest () throws KustvaktException {
- authHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass");
+
+ public VirtualCorpusControllerTest() throws KustvaktException {
+ authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass");
}
@Test
- public void testCreatePrivateVC () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
-
- createVC(authHeader,testUser, "new_vc", json);
-
+ public void testCreatePrivateVC() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ createVC(authHeader, testUser, "new_vc", json);
// list user VC
JsonNode node = listVC(testUser);
assertEquals(2, node.size());
- assertEquals("new_vc", node.get(1).get("name").asText());
-
+ assertEquals(node.get(1).get("name").asText(), "new_vc");
// delete new VC
deleteVC("new_vc", testUser, testUser);
-
// list VC
node = listVC(testUser);
assertEquals(1, node.size());
}
@Test
- public void testCreatePublishedVC () throws KustvaktException {
- String json = "{\"type\": \"PUBLISHED\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
-
+ public void testCreatePublishedVC() throws KustvaktException {
+ String json = "{\"type\": \"PUBLISHED\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new-published-vc";
createVC(authHeader, testUser, vcName, json);
-
// test list owner vc
JsonNode node = retrieveVCInfo(testUser, testUser, vcName);
assertEquals(vcName, node.get("name").asText());
-
// EM: check hidden access
node = listAccessByGroup("admin", "");
node = node.get(node.size() - 1);
- assertEquals("system", node.at("/createdBy").asText());
+ assertEquals(node.at("/createdBy").asText(), "system");
assertEquals(vcName, node.at("/queryName").asText());
assertTrue(node.at("/userGroupName").asText().startsWith("auto"));
assertEquals(vcName, node.at("/queryName").asText());
-
String groupName = node.at("/userGroupName").asText();
-
// EM: check if hidden group has been created
node = testCheckHiddenGroup(groupName);
- assertEquals("HIDDEN", node.at("/status").asText());
-
+ assertEquals(node.at("/status").asText(), "HIDDEN");
// EM: delete vc
deleteVC(vcName, testUser, testUser);
-
// EM: check if the hidden groups are deleted as well
node = testCheckHiddenGroup(groupName);
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
- assertEquals("Group " + groupName + " is not found",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
+ assertEquals("Group " + groupName + " is not found", node.at("/errors/0/1").asText());
}
- private JsonNode testCheckHiddenGroup (String groupName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("@"+groupName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .post(null);
-
+ private JsonNode testCheckHiddenGroup(String groupName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("admin").path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").post(null);
String entity = response.readEntity(String.class);
return JsonUtils.readTree(entity);
}
@Test
- public void testCreateVCWithInvalidToken ()
- throws IOException, KustvaktException {
- String json = "{\"type\": \"PRIVATE\","
- + "\"corpusQuery\": \"corpusSigle=GOE\"}";
-
- InputStream is = getClass().getClassLoader()
- .getResourceAsStream("test-invalid-signature.token");
-
+ public void testCreateVCWithInvalidToken() throws IOException, KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"," + "\"corpusQuery\": \"corpusSigle=GOE\"}";
+ InputStream is = getClass().getClassLoader().getResourceAsStream("test-invalid-signature.token");
String authToken;
- try (BufferedReader reader =
- new BufferedReader(new InputStreamReader(is));) {
+ try (BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
authToken = reader.readLine();
}
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION,
- AuthenticationScheme.BEARER.displayName() + " "
- + authToken)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, AuthenticationScheme.BEARER.displayName() + " " + authToken).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ACCESS_TOKEN,
- node.at("/errors/0/0").asInt());
- assertEquals("Access token is invalid",
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.INVALID_ACCESS_TOKEN, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is invalid");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateVCWithExpiredToken ()
- throws IOException, KustvaktException {
+ public void testCreateVCWithExpiredToken() throws IOException, KustvaktException {
String json = "{\"type\": \"PRIVATE\","
+ "\"corpusQuery\": \"corpusSigle=GOE\"}";
@@ -172,334 +120,192 @@
.header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
.put(Entity.json(json));
+
String entity = response.readEntity(String.class);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.EXPIRED, node.at("/errors/0/0").asInt());
- assertEquals("Access token is expired",
- node.at("/errors/0/1").asText());
-
+ assertEquals(node.at("/errors/0/1").asText(), "Access token is expired");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateSystemVC () throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"pubDate since 1820\"}";
-
+ public void testCreateSystemVC() throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"pubDate since 1820\"}";
String vcName = "new_system_vc";
- Response response = target().path(API_VERSION).path("vc")
- .path("~system").path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("vc").path("~system").path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
JsonNode node = listSystemVC("pearl");
assertEquals(2, node.size());
- assertEquals(ResourceType.SYSTEM.displayName(),
- node.at("/0/type").asText());
- assertEquals(ResourceType.SYSTEM.displayName(),
- node.at("/1/type").asText());
-
- deleteVC(vcName, "system","admin");
-
+ assertEquals(ResourceType.SYSTEM.displayName(), node.at("/0/type").asText());
+ assertEquals(ResourceType.SYSTEM.displayName(), node.at("/1/type").asText());
+ deleteVC(vcName, "system", "admin");
node = listSystemVC("pearl");
assertEquals(1, node.size());
- }
-
- @Test
- public void testCreateSystemVC_unauthorized () throws KustvaktException {
- String json = "{\"type\": \"SYSTEM\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ }
+ @Test
+ public void testCreateSystemVC_unauthorized() throws KustvaktException {
+ String json = "{\"type\": \"SYSTEM\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
testResponseUnauthorized(response, testUser);
}
@Test
- public void testCreateVC_invalidName () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new $vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ public void testCreateVC_invalidName() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new $vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- }
-
-
- @Test
- public void testCreateVC_nameTooShort () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("ne")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
- String entity = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
- JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- assertEquals("queryName must contain at least 3 characters",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
}
@Test
- public void testCreateVC_unauthorized () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\","
- + "\"corpusQuery\": \"creationDate since 1820\"}";
+ public void testCreateVC_nameTooShort() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("ne").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
+ String entity = response.readEntity(String.class);
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ JsonNode node = JsonUtils.readTree(entity);
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "queryName must contain at least 3 characters");
+ }
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ @Test
+ public void testCreateVC_unauthorized() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"," + "\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: guest",
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: guest");
checkWWWAuthenticateHeader(response);
}
@Test
- public void testCreateVC_withoutCorpusQuery () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + "}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ public void testCreateVC_withoutCorpusQuery() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- assertEquals("corpusQuery is null", node.at("/errors/0/1").asText());
- assertEquals("corpusQuery", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "corpusQuery is null");
+ assertEquals(node.at("/errors/0/2").asText(), "corpusQuery");
}
@Test
- public void testCreateVC_withoutEntity () throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(""));
+ public void testCreateVC_withoutEntity() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(""));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- assertEquals("request entity is null", node.at("/errors/0/1").asText());
- assertEquals("request entity", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "request entity is null");
+ assertEquals(node.at("/errors/0/2").asText(), "request entity");
}
@Test
- public void testCreateVC_withoutType () throws KustvaktException {
- String json = "{\"corpusQuery\": " + "\"creationDate since 1820\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + "}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ public void testCreateVC_withoutType() throws KustvaktException {
+ String json = "{\"corpusQuery\": " + "\"creationDate since 1820\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + "}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
// System.out.println(entity);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.INVALID_ARGUMENT,
- node.at("/errors/0/0").asInt());
- assertEquals("type is null", node.at("/errors/0/1").asText());
- assertEquals("type", node.at("/errors/0/2").asText());
+ assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "type is null");
+ assertEquals(node.at("/errors/0/2").asText(), "type");
}
@Test
- public void testCreateVC_withWrongType () throws KustvaktException {
- String json = "{\"type\": \"PRIVAT\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"creationDate since 1820\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~"+testUser).path("new_vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ public void testCreateVC_withWrongType() throws KustvaktException {
+ String json = "{\"type\": \"PRIVAT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"creationDate since 1820\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertTrue(node.at("/errors/0/1").asText().startsWith(
- "Cannot deserialize value of type `de.ids_mannheim.korap.constant."
- + "ResourceType` from String \"PRIVAT\""));
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertTrue(node.at("/errors/0/1").asText().startsWith("Cannot deserialize value of type `de.ids_mannheim.korap.constant." + "ResourceType` from String \"PRIVAT\""));
}
-
- @Test
- public void testMaxNumberOfVC () throws KustvaktException {
- String json = "{\"type\": \"PRIVATE\""
- + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
- for (int i=1; i<6; i++) {
- createVC(authHeader,testUser, "new_vc_"+i, json);
+ @Test
+ public void testMaxNumberOfVC() throws KustvaktException {
+ String json = "{\"type\": \"PRIVATE\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ for (int i = 1; i < 6; i++) {
+ createVC(authHeader, testUser, "new_vc_" + i, json);
}
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~" + testUser).path("new_vc_6").request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
-
+ Response response = target().path(API_VERSION).path("vc").path("~" + testUser).path("new_vc_6").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
- assertEquals(StatusCodes.NOT_ALLOWED,
- node.at("/errors/0/0").asInt());
- assertEquals("Cannot create virtual corpus. The maximum number of "
- + "virtual corpus has been reached.",
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
+ assertEquals("Cannot create virtual corpus. The maximum number of " + "virtual corpus has been reached.", node.at("/errors/0/1").asText());
// list user VC
node = listVC(testUser);
- assertEquals(6, node.size()); // including 1 system-vc
-
+ // including 1 system-vc
+ assertEquals(6, node.size());
// delete new VC
- for (int i=1; i<6; i++) {
- deleteVC("new_vc_"+i, testUser, testUser);
+ for (int i = 1; i < 6; i++) {
+ deleteVC("new_vc_" + i, testUser, testUser);
}
-
// list VC
node = listVC(testUser);
- assertEquals(1, node.size()); // system-vc
+ // system-vc
+ assertEquals(1, node.size());
}
@Test
- public void testDeleteVC_unauthorized () throws KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("dory-vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .delete();
-
- testResponseUnauthorized(response, testUser);
+ public void testDeleteVC_unauthorized() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, authHeader).delete();
+ testResponseUnauthorized(response, testUser);
}
@Test
- public void testEditVC () throws KustvaktException {
+ public void testEditVC() throws KustvaktException {
// 1st edit
String json = "{\"description\": \"edited vc\"}";
editVC("dory", "dory", "dory-vc", json);
-
// check VC
JsonNode node = retrieveVCInfo("dory", "dory", "dory-vc");
- assertEquals("edited vc", node.at("/description").asText());
-
+ assertEquals(node.at("/description").asText(), "edited vc");
// 2nd edit
json = "{\"description\": \"test vc\"}";
editVC("dory", "dory", "dory-vc", json);
-
// check VC
node = retrieveVCInfo("dory", "dory", "dory-vc");
- assertEquals("test vc", node.at("/description").asText());
+ assertEquals(node.at("/description").asText(), "test vc");
}
-
- @Test
- public void testEditVCName () throws KustvaktException {
- String json = "{\"name\": \"new-name\"}";
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("dory-vc").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ @Test
+ public void testEditVCName() throws KustvaktException {
+ String json = "{\"name\": \"new-name\"}";
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testEditCorpusQuery () throws
- ProcessingException, KustvaktException {
+ public void testEditCorpusQuery() throws ProcessingException, KustvaktException {
JsonNode node = testRetrieveKoralQuery("dory", "dory-vc");
- assertEquals("koral:docGroup", node.at("/collection/@type").asText());
- assertEquals("operation:and", node.at("/collection/operation").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/collection/operation").asText(), "operation:and");
assertEquals(2, node.at("/collection/operands").size());
-
String json = "{\"corpusQuery\": \"corpusSigle=WPD17\"}";
editVC("dory", "dory", "dory-vc", json);
-
node = testRetrieveKoralQuery("dory", "dory-vc");
- assertEquals("koral:doc", node.at("/collection/@type").asText());
- assertEquals("corpusSigle", node.at("/collection/key").asText());
- assertEquals("WPD17", node.at("/collection/value").asText());
+ assertEquals(node.at("/collection/@type").asText(), "koral:doc");
+ assertEquals(node.at("/collection/key").asText(), "corpusSigle");
+ assertEquals(node.at("/collection/value").asText(), "WPD17");
}
-
- private JsonNode testRetrieveKoralQuery (String username, String vcName)
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("koralQuery").path("~" + username).path(vcName)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .get();
-
+
+ private JsonNode testRetrieveKoralQuery(String username, String vcName) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("koralQuery").path("~" + username).path(vcName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
@@ -507,64 +313,42 @@
}
@Test
- public void testEditVC_notOwner () throws KustvaktException {
+ public void testEditVC_notOwner() throws KustvaktException {
String json = "{\"description\": \"edited vc\"}";
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("dory-vc")
- .request()
- .header(Attributes.AUTHORIZATION, authHeader)
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .put(Entity.json(json));
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, authHeader).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).put(Entity.json(json));
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: " + testUser,
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals("Unauthorized operation for user: " + testUser, node.at("/errors/0/1").asText());
checkWWWAuthenticateHeader(response);
}
@Test
- public void testPublishProjectVC () throws KustvaktException {
-
+ public void testPublishProjectVC() throws KustvaktException {
String vcName = "group-vc";
-
// check the vc type
JsonNode node = retrieveVCInfo("dory", "dory", vcName);
- assertEquals(ResourceType.PROJECT.displayName(),
- node.get("type").asText());
-
+ assertEquals(ResourceType.PROJECT.displayName(), node.get("type").asText());
// edit vc
String json = "{\"type\": \"PUBLISHED\"}";
editVC("dory", "dory", vcName, json);
-
// check VC
node = testListOwnerVC("dory");
JsonNode n = node.get(1);
- assertEquals(ResourceType.PUBLISHED.displayName(),
- n.get("type").asText());
-
+ assertEquals(ResourceType.PUBLISHED.displayName(), n.get("type").asText());
// check hidden VC access
node = listAccessByGroup("admin", "");
assertEquals(4, node.size());
node = node.get(node.size() - 1);
assertEquals(vcName, node.at("/queryName").asText());
- assertEquals("system", node.at("/createdBy").asText());
+ assertEquals(node.at("/createdBy").asText(), "system");
assertTrue(node.at("/userGroupName").asText().startsWith("auto"));
-
// edit 2nd
json = "{\"type\": \"PROJECT\"}";
editVC("dory", "dory", vcName, json);
-
node = testListOwnerVC("dory");
- assertEquals(ResourceType.PROJECT.displayName(),
- node.get(1).get("type").asText());
-
+ assertEquals(ResourceType.PROJECT.displayName(), node.get(1).get("type").asText());
// check VC access
node = listAccessByGroup("admin", "");
assertEquals(3, node.size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
index fb44266..495e0fc 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusFieldTest.java
@@ -1,15 +1,15 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.IOException;
import org.apache.http.entity.ContentType;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
+
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -29,46 +29,27 @@
@Autowired
private NamedVCLoader vcLoader;
+
@Autowired
private QueryDao dao;
- private JsonNode testRetrieveField (String username, String vcName,
- String field) throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("field").path("~" + username).path(vcName)
- .queryParam("fieldName", field)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .get();
-
+ private JsonNode testRetrieveField(String username, String vcName, String field) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("field").path("~" + username).path(vcName).queryParam("fieldName", field).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testRetrieveProhibitedField (String username, String vcName,
- String field) throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("field").path("~" + username).path(vcName)
- .queryParam("fieldName", field)
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .get();
-
+ private void testRetrieveProhibitedField(String username, String vcName, String field) throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("field").path("~" + username).path(vcName).queryParam("fieldName", field).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/errors/0/0").asInt());
}
-
- private void deleteVcFromDB (String vcName) throws KustvaktException {
+
+ private void deleteVcFromDB(String vcName) throws KustvaktException {
QueryDO vc = dao.retrieveQueryByName(vcName, "system");
dao.deleteQuery(vc);
vc = dao.retrieveQueryByName(vcName, "system");
@@ -76,44 +57,31 @@
}
@Test
- public void testRetrieveFieldsNamedVC1 ()
- throws IOException, QueryException, KustvaktException {
-
+ public void testRetrieveFieldsNamedVC1() throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc1", "/vc/named-vc1.jsonld");
-
JsonNode n = testRetrieveField("system", "named-vc1", "textSigle");
- assertEquals(
- "http://korap.ids-mannheim.de/ns/KoralQuery/v0.3/context.jsonld",
- n.at("/@context").asText());
- assertEquals("textSigle", n.at("/corpus/key").asText());
+ assertEquals(n.at("/@context").asText(), "http://korap.ids-mannheim.de/ns/KoralQuery/v0.3/context.jsonld");
+ assertEquals(n.at("/corpus/key").asText(), "textSigle");
assertEquals(2, n.at("/corpus/value").size());
-
n = testRetrieveField("system", "named-vc1", "author");
assertEquals(2, n.at("/corpus/value").size());
- assertEquals("Goethe, Johann Wolfgang von",
- n.at("/corpus/value/0").asText());
-
+ assertEquals(n.at("/corpus/value/0").asText(), "Goethe, Johann Wolfgang von");
testRetrieveUnknownTokens();
testRetrieveProhibitedField("system", "named-vc1", "tokens");
testRetrieveProhibitedField("system", "named-vc1", "base");
-
VirtualCorpusCache.delete("named-vc1");
-
deleteVcFromDB("named-vc1");
}
- private void testRetrieveUnknownTokens () throws
- ProcessingException, KustvaktException {
+ private void testRetrieveUnknownTokens() throws ProcessingException, KustvaktException {
JsonNode n = testRetrieveField("system", "named-vc1", "unknown");
- assertEquals("unknown", n.at("/corpus/key").asText());
+ assertEquals(n.at("/corpus/key").asText(), "unknown");
assertEquals(0, n.at("/corpus/value").size());
}
@Test
- public void testRetrieveTextSigleNamedVC2 ()
- throws IOException, QueryException, KustvaktException {
+ public void testRetrieveTextSigleNamedVC2() throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc2", "/vc/named-vc2.jsonld");
-
JsonNode n = testRetrieveField("system", "named-vc2", "textSigle");
assertEquals(2, n.at("/corpus/value").size());
VirtualCorpusCache.delete("named-vc2");
@@ -121,39 +89,25 @@
}
@Test
- public void testRetrieveTextSigleNamedVC3 ()
- throws IOException, QueryException, KustvaktException {
+ public void testRetrieveTextSigleNamedVC3() throws IOException, QueryException, KustvaktException {
vcLoader.loadVCToCache("named-vc3", "/vc/named-vc3.jsonld");
-
JsonNode n = testRetrieveField("system", "named-vc3", "textSigle");
n = n.at("/corpus/value");
assertEquals(1, n.size());
- assertEquals("GOE/AGI/00000", n.get(0).asText());
-
+ assertEquals(n.get(0).asText(), "GOE/AGI/00000");
VirtualCorpusCache.delete("named-vc3");
deleteVcFromDB("named-vc3");
}
-
- @Test
- public void testRetrieveFieldUnauthorized () throws KustvaktException, IOException, QueryException {
- vcLoader.loadVCToCache("named-vc3", "/vc/named-vc3.jsonld");
-
- Response response = target().path(API_VERSION).path("vc")
- .path("field").path("~system").path("named-vc3")
- .queryParam("fieldName", "textSigle")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON)
- .get();
+ @Test
+ public void testRetrieveFieldUnauthorized() throws KustvaktException, IOException, QueryException {
+ vcLoader.loadVCToCache("named-vc3", "/vc/named-vc3.jsonld");
+ Response response = target().path(API_VERSION).path("vc").path("field").path("~system").path("named-vc3").queryParam("fieldName", "textSigle").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON).get();
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: dory", node.at("/errors/0/1").asText());
-
-
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: dory");
VirtualCorpusCache.delete("named-vc3");
deleteVcFromDB("named-vc3");
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
index ab04741..2fe7a47 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusInfoTest.java
@@ -1,7 +1,7 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
@@ -10,11 +10,9 @@
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.ResourceType;
@@ -24,116 +22,68 @@
public class VirtualCorpusInfoTest extends VirtualCorpusTestBase {
private String admin = "admin";
- private String testUser = "VirtualCorpusInfoTest";
-
-
- @Test
- public void testRetrieveSystemVC() throws
- ProcessingException, KustvaktException {
+ private String testUser = "VirtualCorpusInfoTest";
+
+ @Test
+ public void testRetrieveSystemVC() throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo(testUser, "system", "system-vc");
- assertEquals("system-vc", node.at("/name").asText());
- assertEquals(ResourceType.SYSTEM.displayName(),
- node.at("/type").asText());
-// assertEquals("koral:doc", node.at("/koralQuery/collection/@type").asText());
+ assertEquals(node.at("/name").asText(), "system-vc");
+ assertEquals(ResourceType.SYSTEM.displayName(), node.at("/type").asText());
+ // assertEquals("koral:doc", node.at("/koralQuery/collection/@type").asText());
assertTrue(node.at("/query").isMissingNode());
assertTrue(node.at("/queryLanguage").isMissingNode());
}
@Test
- public void testRetrieveSystemVCGuest () throws
- ProcessingException, KustvaktException {
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~system").path("system-vc")
- .request()
- .get();
+ public void testRetrieveSystemVCGuest() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~system").path("system-vc").request().get();
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
- assertEquals("system-vc", node.at("/name").asText());
- assertEquals(ResourceType.SYSTEM.displayName(),
- node.at("/type").asText());
+ assertEquals(node.at("/name").asText(), "system-vc");
+ assertEquals(ResourceType.SYSTEM.displayName(), node.at("/type").asText());
}
@Test
- public void testRetrieveOwnerPrivateVC()
- throws ProcessingException,
- KustvaktException {
-
+ public void testRetrieveOwnerPrivateVC() throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("dory", "dory", "dory-vc");
- assertEquals("dory-vc", node.at("/name").asText());
- assertEquals(ResourceType.PRIVATE.displayName(),
- node.at("/type").asText());
+ assertEquals(node.at("/name").asText(), "dory-vc");
+ assertEquals(ResourceType.PRIVATE.displayName(), node.at("/type").asText());
}
@Test
- public void testRetrievePrivateVCUnauthorized ()
- throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory")
- .path("dory-vc").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .get();
+ public void testRetrievePrivateVCUnauthorized() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).get();
testResponseUnauthorized(response, testUser);
}
@Test
- public void testRetrieveProjectVC() throws
- ProcessingException, KustvaktException {
-
+ public void testRetrieveProjectVC() throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("nemo", "dory", "group-vc");
- assertEquals("group-vc", node.at("/name").asText());
- assertEquals(ResourceType.PROJECT.displayName(),
- node.at("/type").asText());
+ assertEquals(node.at("/name").asText(), "group-vc");
+ assertEquals(ResourceType.PROJECT.displayName(), node.at("/type").asText());
}
-
- @Test
- public void testRetrieveProjectVCUnauthorized () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("group-vc")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass"))
- .get();
+ @Test
+ public void testRetrieveProjectVCUnauthorized() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass")).get();
testResponseUnauthorized(response, testUser);
}
-
@Test
- public void testRetrieveProjectVCbyNonActiveMember ()
- throws ProcessingException,
- KustvaktException {
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("group-vc")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("marlin", "pass"))
- .get();
+ public void testRetrieveProjectVCbyNonActiveMember() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("marlin", "pass")).get();
testResponseUnauthorized(response, "marlin");
}
@Test
- public void testRetrievePublishedVC () throws
- ProcessingException, KustvaktException {
-
+ public void testRetrievePublishedVC() throws ProcessingException, KustvaktException {
JsonNode node = retrieveVCInfo("gill", "marlin", "published-vc");
- assertEquals("published-vc", node.at("/name").asText());
- assertEquals(ResourceType.PUBLISHED.displayName(),
- node.at("/type").asText());
-
+ assertEquals(node.at("/name").asText(), "published-vc");
+ assertEquals(ResourceType.PUBLISHED.displayName(), node.at("/type").asText());
Form f = new Form();
f.param("status", "HIDDEN");
// check gill in the hidden group of the vc
- Response response = target().path(API_VERSION)
- .path("admin").path("group").path("list")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED)
- .post(Entity.form(f));
-
+ Response response = target().path(API_VERSION).path("admin").path("group").path("list").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED).post(Entity.form(f));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
@@ -141,45 +91,24 @@
String members = node.at("/0/members").toString();
assertTrue(members.contains("\"userId\":\"gill\""));
}
-
+
@Test
- public void testAdminRetrievePrivateVC () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("dory-vc")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .get();
-
+ public void testAdminRetrievePrivateVC() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("dory-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(1, node.at("/id").asInt());
- assertEquals("dory-vc", node.at("/name").asText());
+ assertEquals(node.at("/name").asText(), "dory-vc");
}
+
@Test
- public void testAdminRetrieveProjectVC () throws
- ProcessingException, KustvaktException {
-
- Response response = target().path(API_VERSION).path("vc")
- .path("~dory").path("group-vc")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(admin, "pass"))
- .get();
+ public void testAdminRetrieveProjectVC() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").path("group-vc").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(admin, "pass")).get();
String entity = response.readEntity(String.class);
-
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
JsonNode node = JsonUtils.readTree(entity);
- assertEquals("group-vc", node.at("/name").asText());
- assertEquals(ResourceType.PROJECT.displayName(),
- node.at("/type").asText());
+ assertEquals(node.at("/name").asText(), "group-vc");
+ assertEquals(ResourceType.PROJECT.displayName(), node.at("/type").asText());
}
-
-
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
index 35fceb7..7e794d2 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusListTest.java
@@ -1,17 +1,15 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Ignore;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.exceptions.KustvaktException;
@@ -21,84 +19,56 @@
public class VirtualCorpusListTest extends VirtualCorpusTestBase {
@Test
- public void testListVCNemo ()
- throws ProcessingException, KustvaktException {
-
+ public void testListVCNemo() throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("nemo");
assertEquals(1, node.size());
-
node = listSystemVC("nemo");
assertEquals(1, node.size());
-
node = listVC("nemo");
assertEquals(3, node.size());
}
@Test
- public void testListVCPearl ()
- throws ProcessingException, KustvaktException {
+ public void testListVCPearl() throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("pearl");
assertEquals(0, node.size());
-
node = listVC("pearl");
- assertEquals(2, node.size());
+ assertEquals(2, node.size());
}
@Test
- public void testListVCDory ()
- throws ProcessingException, KustvaktException {
+ public void testListVCDory() throws ProcessingException, KustvaktException {
JsonNode node = testListOwnerVC("dory");
assertEquals(2, node.size());
-
node = listVC("dory");
assertEquals(4, node.size());
}
-
@Test
- public void testListAvailableVCGuest ()
- throws ProcessingException, KustvaktException {
- Response response =
- target().path(API_VERSION).path("vc").request().get();
+ public void testListAvailableVCGuest() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").request().get();
testResponseUnauthorized(response, "guest");
}
- @Ignore
+ @Disabled
@Deprecated
@Test
- public void testListAvailableVCByOtherUser ()
- throws ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc").path("~dory")
- .request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("pearl", "pass"))
- .get();
+ public void testListAvailableVCByOtherUser() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").path("~dory").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("pearl", "pass")).get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
- assertEquals(StatusCodes.AUTHORIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Unauthorized operation for user: pearl",
- node.at("/errors/0/1").asText());
-
+ assertEquals(StatusCodes.AUTHORIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Unauthorized operation for user: pearl");
checkWWWAuthenticateHeader(response);
}
-
- @Ignore
+
+ @Disabled
@Deprecated
@Test
- public void testListUserVC () throws
- ProcessingException, KustvaktException {
- Response response = target().path(API_VERSION).path("vc")
- .queryParam("username", "dory")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("admin", "pass"))
- .get();
-
+ public void testListUserVC() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("vc").queryParam("username", "dory").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("admin", "pass")).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(4, node.size());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
index 7691965..120a5fa 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusSharingTest.java
@@ -1,7 +1,7 @@
package de.ids_mannheim.korap.web.controller;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import javax.ws.rs.ProcessingException;
import javax.ws.rs.client.Entity;
@@ -10,10 +10,8 @@
import javax.ws.rs.core.Response.Status;
import org.apache.http.HttpStatus;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.constant.GroupMemberStatus;
@@ -23,212 +21,129 @@
import de.ids_mannheim.korap.utils.JsonUtils;
public class VirtualCorpusSharingTest extends VirtualCorpusTestBase {
+
private String testUser = "VirtualCorpusSharingTest";
@Test
- public void testShareUnknownVC () throws
- ProcessingException, KustvaktException {
- Response response = testShareVCByCreator("marlin",
- "non-existing-vc", "marlin group");
+ public void testShareUnknownVC() throws ProcessingException, KustvaktException {
+ Response response = testShareVCByCreator("marlin", "non-existing-vc", "marlin group");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
}
@Test
- public void testShareUnknownGroup () throws
- ProcessingException, KustvaktException {
- Response response = testShareVCByCreator("marlin", "marlin-vc",
- "non-existing-group");
+ public void testShareUnknownGroup() throws ProcessingException, KustvaktException {
+ Response response = testShareVCByCreator("marlin", "marlin-vc", "non-existing-group");
JsonNode node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(HttpStatus.SC_NOT_FOUND, response.getStatus());
- assertEquals(StatusCodes.NO_RESOURCE_FOUND,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
}
@Test
- public void testShareVC_notOwner () throws
- ProcessingException, KustvaktException {
-
+ public void testShareVC_notOwner() throws ProcessingException, KustvaktException {
// dory is VCA in marlin group
- Response response = target().path(API_VERSION).path("vc")
- .path("~marlin").path("marlin-vc").path("share")
- .path("@marlin group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("dory", "pass"))
- .post(Entity.form(new Form()));
-
+ Response response = target().path(API_VERSION).path("vc").path("~marlin").path("marlin-vc").path("share").path("@marlin group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("dory", "pass")).post(Entity.form(new Form()));
testResponseUnauthorized(response, "dory");
}
-
+
@Test
- public void testShareVC_byMember () throws
- ProcessingException, KustvaktException {
-
+ public void testShareVC_byMember() throws ProcessingException, KustvaktException {
// nemo is not VCA in marlin group
- Response response = target().path(API_VERSION).path("vc")
- .path("~nemo").path("nemo-vc").path("share").path("@marlin-group")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("nemo", "pass"))
- .post(Entity.form(new Form()));
-
+ Response response = target().path(API_VERSION).path("vc").path("~nemo").path("nemo-vc").path("share").path("@marlin-group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("nemo", "pass")).post(Entity.form(new Form()));
testResponseUnauthorized(response, "nemo");
}
-
+
@Test
- public void testCreateShareProjectVC () throws KustvaktException {
- String json =
- "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\""
- + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
+ public void testCreateShareProjectVC() throws KustvaktException {
+ String json = "{\"type\": \"PROJECT\"" + ",\"queryType\": \"VIRTUAL_CORPUS\"" + ",\"corpusQuery\": \"corpusSigle=GOE\"}";
String vcName = "new_project_vc";
- String authHeader = HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(testUser, "pass");
-
+ String authHeader = HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(testUser, "pass");
createVC(authHeader, testUser, vcName, json);
-
// retrieve vc info
JsonNode vcInfo = retrieveVCInfo(testUser, testUser, vcName);
assertEquals(vcName, vcInfo.get("name").asText());
-
// list user VC
JsonNode node = listVC(testUser);
assertEquals(2, node.size());
assertEquals(vcName, node.get(1).get("name").asText());
-
// search by non member
Response response = searchWithVCRef("dory", testUser, vcName);
assertEquals(Status.UNAUTHORIZED.getStatusCode(), response.getStatus());
-
// create user group
String groupName = "owidGroup";
String memberName = "darla";
-
response = createUserGroup(testUser, groupName, "Owid users");
assertEquals(Status.CREATED.getStatusCode(), response.getStatus());
-
listUserGroup(testUser, groupName);
testInviteMember(testUser, groupName, "darla");
subscribeToGroup(memberName, groupName);
checkMemberInGroup(memberName, testUser, groupName);
-
// share vc to group
testShareVCByCreator(testUser, vcName, groupName);
node = listAccessByGroup(testUser, groupName);
-
// search by member
response = searchWithVCRef(memberName, testUser, vcName);
assertEquals(Status.OK.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertTrue(node.at("/matches").size() > 0);
-
// delete project VC
deleteVC(vcName, testUser, testUser);
-
// list VC
node = listVC(testUser);
assertEquals(1, node.size());
-
// search by member
response = searchWithVCRef(memberName, testUser, vcName);
assertEquals(Status.NOT_FOUND.getStatusCode(), response.getStatus());
node = JsonUtils.readTree(response.readEntity(String.class));
assertEquals(StatusCodes.NO_RESOURCE_FOUND, node.at("/errors/0/0").asInt());
-
}
- private Response createUserGroup (String username, String groupName,
- String description) throws ProcessingException, KustvaktException {
+ private Response createUserGroup(String username, String groupName, String description) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("description", description);
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .put(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).put(Entity.form(form));
return response;
}
- private JsonNode listUserGroup (String username, String groupName)
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("group").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .get();
-
+ private JsonNode listUserGroup(String username, String groupName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
return node;
}
- private void testInviteMember (String username, String groupName,
- String memberName) throws ProcessingException, KustvaktException {
+ private void testInviteMember(String username, String groupName, String memberName) throws ProcessingException, KustvaktException {
Form form = new Form();
form.param("members", memberName);
-
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("invite").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("invite").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(form));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
// list group
JsonNode node = listUserGroup(username, groupName);
node = node.get(0);
assertEquals(2, node.get("members").size());
-
assertEquals(memberName, node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.PENDING.name(),
- node.at("/members/1/status").asText());
+ assertEquals(GroupMemberStatus.PENDING.name(), node.at("/members/1/status").asText());
assertEquals(0, node.at("/members/1/roles").size());
}
- private void subscribeToGroup (String username, String groupName)
- throws KustvaktException {
- Response response = target().path(API_VERSION).path("group")
- .path("@" + groupName).path("subscribe").request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .post(Entity.form(new Form()));
-
+ private void subscribeToGroup(String username, String groupName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("group").path("@" + groupName).path("subscribe").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).post(Entity.form(new Form()));
assertEquals(Status.OK.getStatusCode(), response.getStatus());
}
- private void checkMemberInGroup (String memberName, String testUser,
- String groupName) throws KustvaktException {
-
+ private void checkMemberInGroup(String memberName, String testUser, String groupName) throws KustvaktException {
JsonNode node = listUserGroup(testUser, groupName).get(0);
assertEquals(2, node.get("members").size());
-
assertEquals(memberName, node.at("/members/1/userId").asText());
- assertEquals(GroupMemberStatus.ACTIVE.name(),
- node.at("/members/1/status").asText());
- assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(),
- node.at("/members/1/roles/1").asText());
- assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(),
- node.at("/members/1/roles/0").asText());
+ assertEquals(GroupMemberStatus.ACTIVE.name(), node.at("/members/1/status").asText());
+ assertEquals(PredefinedRole.VC_ACCESS_MEMBER.name(), node.at("/members/1/roles/1").asText());
+ assertEquals(PredefinedRole.USER_GROUP_MEMBER.name(), node.at("/members/1/roles/0").asText());
}
- private Response searchWithVCRef (String username, String vcCreator,
- String vcName) throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("cq",
- "referTo \"" + vcCreator + "/" + vcName + "\"")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue(username, "pass"))
- .get();
-
+ private Response searchWithVCRef(String username, String vcCreator, String vcName) throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("cq", "referTo \"" + vcCreator + "/" + vcName + "\"").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue(username, "pass")).get();
return response;
}
-
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
index 7b354b5..821a338 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/controller/VirtualCorpusTestBase.java
@@ -3,7 +3,7 @@
import static org.hamcrest.CoreMatchers.hasItem;
import static org.hamcrest.CoreMatchers.not;
import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.List;
import java.util.Map.Entry;
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
index 6416879..2b3cd0c 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/InfoControllerTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.junit.Test;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import javax.ws.rs.core.Response;
@@ -24,27 +23,17 @@
@Autowired
private SearchKrill krill;
-
+
@Test
- public void testInfo () throws KustvaktException {
- Response response = target().path(API_VERSION).path("info")
- .request()
- .get();
-
+ public void testInfo() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("info").request().get();
assertEquals(Status.OK.getStatusCode(), response.getStatus());
-
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(config.getCurrentVersion(),
- node.at("/latest_api_version").asText());
- assertEquals(config.getSupportedVersions().size(),
- node.at("/supported_api_versions").size());
-
- assertEquals(ServiceInfo.getInfo().getVersion(),
- node.at("/kustvakt_version").asText());
- assertEquals(krill.getIndex().getVersion(),
- node.at("/krill_version").asText());
- assertEquals(ServiceInfo.getInfo().getKoralVersion(),
- node.at("/koral_version").asText());
+ assertEquals(config.getCurrentVersion(), node.at("/latest_api_version").asText());
+ assertEquals(config.getSupportedVersions().size(), node.at("/supported_api_versions").size());
+ assertEquals(ServiceInfo.getInfo().getVersion(), node.at("/kustvakt_version").asText());
+ assertEquals(krill.getIndex().getVersion(), node.at("/krill_version").asText());
+ assertEquals(ServiceInfo.getInfo().getKoralVersion(), node.at("/koral_version").asText());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
index 56b861f..7746eae 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteMultipleCorpusQueryTest.java
@@ -1,10 +1,9 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import javax.ws.rs.ProcessingException;
@@ -19,71 +18,47 @@
public class LiteMultipleCorpusQueryTest extends LiteJerseyTest {
@Test
- public void testSearchGet () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "das").queryParam("ql", "poliqarp")
- .queryParam("cq", "pubPlace=München")
- .queryParam("cq", "textSigle=\"GOE/AGA/01784\"")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchGet() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "das").queryParam("ql", "poliqarp").queryParam("cq", "pubPlace=München").queryParam("cq", "textSigle=\"GOE/AGA/01784\"").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
node = node.at("/collection");
- assertEquals("koral:docGroup", node.at("/@type").asText());
- assertEquals("operation:and", node.at("/operation").asText());
+ assertEquals(node.at("/@type").asText(), "koral:docGroup");
+ assertEquals(node.at("/operation").asText(), "operation:and");
assertEquals(2, node.at("/operands").size());
- assertEquals("koral:doc", node.at("/operands/0/@type").asText());
- assertEquals("match:eq", node.at("/operands/0/match").asText());
- assertEquals("pubPlace", node.at("/operands/0/key").asText());
- assertEquals("München", node.at("/operands/0/value").asText());
- assertEquals("textSigle", node.at("/operands/1/key").asText());
- assertEquals("GOE/AGA/01784", node.at("/operands/1/value").asText());
+ assertEquals(node.at("/operands/0/@type").asText(), "koral:doc");
+ assertEquals(node.at("/operands/0/match").asText(), "match:eq");
+ assertEquals(node.at("/operands/0/key").asText(), "pubPlace");
+ assertEquals(node.at("/operands/0/value").asText(), "München");
+ assertEquals(node.at("/operands/1/key").asText(), "textSigle");
+ assertEquals(node.at("/operands/1/value").asText(), "GOE/AGA/01784");
}
@Test
- public void testStatisticsWithMultipleCq ()
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("statistics")
- .queryParam("cq", "textType=Abhandlung")
- .queryParam("cq", "corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithMultipleCq() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung").queryParam("cq", "corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
@Test
- public void testStatisticsWithMultipleCorpusQuery ()
- throws ProcessingException,
- KustvaktException {
- Response response = target().path(API_VERSION).path("statistics")
- .queryParam("corpusQuery", "textType=Autobiographie")
- .queryParam("corpusQuery", "corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithMultipleCorpusQuery() throws ProcessingException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie").queryParam("corpusQuery", "corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(9, node.at("/documents").asInt());
assertEquals(527662, node.at("/tokens").asInt());
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
-
- assertEquals(StatusCodes.DEPRECATED,
- node.at("/warnings/0/0").asInt());
- assertEquals("Parameter corpusQuery is deprecated in favor of cq.",
- node.at("/warnings/0/1").asText());
+ assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
index a052c70..0ec56c6 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchControllerTest.java
@@ -1,15 +1,14 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
@@ -17,13 +16,11 @@
import javax.ws.rs.core.Response.Status;
import org.eclipse.jetty.http.HttpStatus;
-import org.junit.Ignore;
-import org.junit.Test;
+import org.junit.jupiter.api.Disabled;
+import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
import com.google.common.net.HttpHeaders;
-
import de.ids_mannheim.korap.authentication.http.HttpAuthorizationHandler;
import de.ids_mannheim.korap.config.Attributes;
import de.ids_mannheim.korap.config.KustvaktConfiguration;
@@ -38,101 +35,68 @@
@Autowired
private SearchKrill searchKrill;
+
@Autowired
private KustvaktConfiguration config;
-// EM: The API is disabled
- @Ignore
+ // EM: The API is disabled
+ @Disabled
@Test
- public void testGetJSONQuery () throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetJSONQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
- assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
- assertEquals("sentence", node.at("/meta/context").asText());
- assertEquals("13", node.at("/meta/count").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
+ assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
+ assertEquals(node.at("/meta/context").asText(), "sentence");
+ assertEquals(node.at("/meta/count").asText(), "13");
}
-
-// EM: The API is disabled
- @Ignore
- @Test
- public void testbuildAndPostQuery () throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ // EM: The API is disabled
+ @Disabled
+ @Test
+ public void testbuildAndPostQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
-
- response = target().path(API_VERSION).path("search")
- .request()
- .post(Entity.json(query));
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("search").request().post(Entity.json(query));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String matches = response.readEntity(String.class);
JsonNode match_node = JsonUtils.readTree(matches);
assertNotEquals(0, match_node.path("matches").size());
}
@Test
- public void testApiWelcomeMessage () {
- Response response = target().path(API_VERSION).path("")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testApiWelcomeMessage() {
+ Response response = target().path(API_VERSION).path("").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String message = response.readEntity(String.class);
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
assertEquals(message, config.getApiWelcomeMessage());
}
@Test
- public void testQueryGet () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testQueryGet() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
- assertEquals("base/s:s", node.at("/meta/context").asText());
- assertEquals("13", node.at("/meta/count").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
+ assertEquals(node.at("/meta/context").asText(), "base/s:s");
+ assertEquals(node.at("/meta/count").asText(), "13");
assertNotEquals(0, node.at("/matches").size());
}
@Test
- public void testQueryFailure () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das").queryParam("ql", "poliqarp")
- .queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE")
- .queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testQueryFailure() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das").queryParam("ql", "poliqarp").queryParam("cq", "corpusSigle=WPD | corpusSigle=GOE").queryParam("count", "13").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
assertEquals(302, node.at("/errors/0/0").asInt());
@@ -143,448 +107,282 @@
}
@Test
- public void testFoundryRewrite () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testFoundryRewrite() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
- assertEquals("opennlp", node.at("/query/wrap/foundry").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
+ assertEquals(node.at("/query/wrap/foundry").asText(), "opennlp");
}
-// EM: The API is disabled
+ // EM: The API is disabled
@Test
- @Ignore
- public void testQueryPost () throws KustvaktException {
+ @Disabled
+ public void testQueryPost() throws KustvaktException {
QuerySerializer s = new QuerySerializer();
s.setQuery("[orth=das]", "poliqarp");
-
- Response response = target().path(API_VERSION).path("search")
- .request()
- .post(Entity.json(s.toJSON()));
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ Response response = target().path(API_VERSION).path("search").request().post(Entity.json(s.toJSON()));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
assertNotEquals(0, node.at("/matches").size());
}
@Test
- public void testParameterField () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("fields", "author,docSigle")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testParameterField() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", "author,docSigle").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
assertNotEquals(0, node.at("/matches").size());
- assertEquals("[\"author\",\"docSigle\"]",
- node.at("/meta/fields").toString());
+ assertEquals(node.at("/meta/fields").toString(), "[\"author\",\"docSigle\"]");
}
@Test
- public void testMatchInfoGetWithoutSpans () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
- .queryParam("foundry", "*").queryParam("spans", "false")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMatchInfoGetWithoutSpans() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "*").queryParam("spans", "false").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals("match-GOE/AGA/01784-p36-46(5)37-45(2)38-42",
- node.at("/matchID").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- };
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ }
@Test
- public void testMatchInfoGetWithoutHighlights () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
- .queryParam("foundry", "xy").queryParam("spans", "false")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMatchInfoGetWithoutHighlights() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "xy").queryParam("spans", "false").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals(
- "<span class=\"context-left\"></span><span class=\"match\">der alte freie Weg nach Mainz war gesperrt, ich mußte über die Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark> auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span><span class=\"context-right\"></span>",
- node.at("/snippet").asText());
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals("match-GOE/AGA/01784-p36-46(5)37-45(2)38-42",
- node.at("/matchID").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- };
+ assertEquals(node.at("/snippet").asText(), "<span class=\"context-left\"></span><span class=\"match\">der alte freie Weg nach Mainz war gesperrt, ich mußte über die Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark> auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span><span class=\"context-right\"></span>");
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ }
@Test
- public void testMatchInfoWithoutExtension () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42")
- .queryParam("foundry", "-").queryParam("spans", "false")
- .queryParam("expand","false")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMatchInfoWithoutExtension() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42").queryParam("foundry", "-").queryParam("spans", "false").queryParam("expand", "false").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals("match-GOE/AGA/01784-p36-46(5)37-45(2)38-42",
- node.at("/matchID").asText());
- assertEquals("<span class=\"context-left\"><span class=\"more\"></span></span><span class=\"match\"><mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark></span><span class=\"context-right\"><span class=\"more\"></span></span>",
- node.at("/snippet").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- };
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/snippet").asText(), "<span class=\"context-left\"><span class=\"more\"></span></span><span class=\"match\"><mark>gefüttert; der Ort ist sehr zerschossen; dann über die Schiffbrücke</mark></span><span class=\"context-right\"><span class=\"more\"></span></span>");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ }
-
@Test
- public void testMatchInfoGetWithHighlights () throws KustvaktException {
- Response response = target().path(API_VERSION)
- .path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo")
- .queryParam("foundry", "xy").queryParam("spans", "false")
- .queryParam("hls", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMatchInfoGetWithHighlights() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46(5)37-45(2)38-42/matchInfo").queryParam("foundry", "xy").queryParam("spans", "false").queryParam("hls", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals(
- "<span class=\"context-left\"></span><span class=\"match\">"
- + "der alte freie Weg nach Mainz war gesperrt, ich mußte über die "
- + "Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; "
- + "<mark class=\"class-5 level-0\">der <mark class=\"class-2 level-1\">"
- + "Ort ist sehr zerschossen; dann</mark> über die Schiffbrücke</mark></mark> "
- + "auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem "
- + "zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span>"
- + "<span class=\"context-right\"></span>",
- node.at("/snippet").asText());
- assertEquals("match-GOE/AGA/01784-p36-46(5)37-45(2)38-42",
- node.at("/matchID").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- };
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals("<span class=\"context-left\"></span><span class=\"match\">" + "der alte freie Weg nach Mainz war gesperrt, ich mußte über die " + "Schiffbrücke bei Rüsselsheim; in Ginsheim ward <mark>gefüttert; " + "<mark class=\"class-5 level-0\">der <mark class=\"class-2 level-1\">" + "Ort ist sehr zerschossen; dann</mark> über die Schiffbrücke</mark></mark> " + "auf die Nonnenaue, wo viele Bäume niedergehauen lagen, sofort auf dem " + "zweiten Teil der Schiffbrücke über den größern Arm des Rheins.</span>" + "<span class=\"context-right\"></span>", node.at("/snippet").asText());
+ assertEquals(node.at("/matchID").asText(), "match-GOE/AGA/01784-p36-46(5)37-45(2)38-42");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ }
@Test
- public void testMatchInfoGet2 () throws KustvaktException {
- Response response = target().path(API_VERSION)
-
- .path("corpus/GOE/AGA/01784/p36-46/matchInfo")
- .queryParam("foundry", "*")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMatchInfoGet2() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("corpus/GOE/AGA/01784/p36-46/matchInfo").queryParam("foundry", "*").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
assertNotNull(node);
- assertEquals("GOE/AGA/01784", node.at("/textSigle").asText());
- assertEquals("Belagerung von Mainz", node.at("/title").asText());
- };
-
-// EM: The API is disabled
- @Ignore
+ assertEquals(node.at("/textSigle").asText(), "GOE/AGA/01784");
+ assertEquals(node.at("/title").asText(), "Belagerung von Mainz");
+ }
+
+ // EM: The API is disabled
+ @Disabled
@Test
- public void testCollectionQueryParameter () throws KustvaktException {
- Response response = target().path(API_VERSION).path("query")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("fields", "author, docSigle")
- .queryParam("context", "sentence").queryParam("count", "13")
- .queryParam("cq", "textClass=Politik & corpus=WPD")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testCollectionQueryParameter() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("query").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", "author, docSigle").queryParam("context", "sentence").queryParam("count", "13").queryParam("cq", "textClass=Politik & corpus=WPD").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
- assertEquals("Politik",
- node.at("/collection/operands/0/value").asText());
- assertEquals("WPD", node.at("/collection/operands/1/value").asText());
-
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("fields", "author, docSigle")
- .queryParam("context", "sentence").queryParam("count", "13")
- .queryParam("cq", "textClass=Politik & corpus=WPD")
- .request()
- .get();
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "Politik");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
+ response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("fields", "author, docSigle").queryParam("context", "sentence").queryParam("count", "13").queryParam("cq", "textClass=Politik & corpus=WPD").request().get();
// String version =
// LucenePackage.get().getImplementationVersion();;
// System.out.println("VERSION "+ version);
// System.out.println("RESPONSE "+ response);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
query = response.readEntity(String.class);
node = JsonUtils.readTree(query);
assertNotNull(node);
- assertEquals("orth", node.at("/query/wrap/layer").asText());
- assertEquals("Politik",
- node.at("/collection/operands/0/value").asText());
- assertEquals("WPD", node.at("/collection/operands/1/value").asText());
+ assertEquals(node.at("/query/wrap/layer").asText(), "orth");
+ assertEquals(node.at("/collection/operands/0/value").asText(), "Politik");
+ assertEquals(node.at("/collection/operands/1/value").asText(), "WPD");
}
@Test
- public void testTokenRetrieval () throws KustvaktException {
- Response response =
- target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105/")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testTokenRetrieval() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105/").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String resp = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(resp);
assertTrue(node.at("/hasSnippet").asBoolean());
assertFalse(node.at("/hasTokens").asBoolean());
assertTrue(node.at("/tokens").isMissingNode());
- assertEquals(
- "<span class=\"context-left\"><span class=\"more\"></span></span>"+
- "<span class=\"match\"><mark>die</mark></span>"+
- "<span class=\"context-right\"><span class=\"more\"></span></span>",
- node.at("/snippet").asText());
-
+ assertEquals("<span class=\"context-left\"><span class=\"more\"></span></span>" + "<span class=\"match\"><mark>die</mark></span>" + "<span class=\"context-right\"><span class=\"more\"></span></span>", node.at("/snippet").asText());
// Tokens
- response =
- target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105")
- .queryParam("show-snippet", "false")
- .queryParam("show-tokens", "true")
- .queryParam("expand", "false")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784/p104-105").queryParam("show-snippet", "false").queryParam("show-tokens", "true").queryParam("expand", "false").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
resp = response.readEntity(String.class);
node = JsonUtils.readTree(resp);
-
assertFalse(node.at("/hasSnippet").asBoolean());
assertTrue(node.at("/hasTokens").asBoolean());
assertTrue(node.at("/snippet").isMissingNode());
- assertEquals(
- "die",
- node.at("/tokens/match/0").asText());
+ assertEquals(node.at("/tokens/match/0").asText(), "die");
assertTrue(node.at("/tokens/match/1").isMissingNode());
- };
+ }
-
@Test
- public void testMetaFields () throws KustvaktException {
- Response response =
- target().path(API_VERSION).path("/corpus/GOE/AGA/01784")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testMetaFields() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("/corpus/GOE/AGA/01784").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String resp = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(resp);
// System.err.println(node.toString());
-
Iterator<JsonNode> fieldIter = node.at("/document/fields").elements();
-
int checkC = 0;
while (fieldIter.hasNext()) {
JsonNode field = (JsonNode) fieldIter.next();
-
String key = field.at("/key").asText();
-
- assertEquals("koral:field", field.at("/@type").asText());
-
+ assertEquals(field.at("/@type").asText(), "koral:field");
switch (key) {
case "textSigle":
- assertEquals("type:string", field.at("/type").asText());
- assertEquals("GOE/AGA/01784", field.at("/value").asText());
+ assertEquals(field.at("/type").asText(), "type:string");
+ assertEquals(field.at("/value").asText(), "GOE/AGA/01784");
checkC++;
break;
case "author":
- assertEquals("type:text", field.at("/type").asText());
- assertEquals("Goethe, Johann Wolfgang von",
- field.at("/value").asText());
+ assertEquals(field.at("/type").asText(), "type:text");
+ assertEquals(field.at("/value").asText(), "Goethe, Johann Wolfgang von");
checkC++;
break;
case "docSigle":
- assertEquals("type:string", field.at("/type").asText());
- assertEquals("GOE/AGA", field.at("/value").asText());
+ assertEquals(field.at("/type").asText(), "type:string");
+ assertEquals(field.at("/value").asText(), "GOE/AGA");
checkC++;
break;
case "docTitle":
- assertEquals("type:text", field.at("/type").asText());
- assertEquals(
- "Goethe: Autobiographische Schriften II, (1817-1825, 1832)",
- field.at("/value").asText());
+ assertEquals(field.at("/type").asText(), "type:text");
+ assertEquals(field.at("/value").asText(), "Goethe: Autobiographische Schriften II, (1817-1825, 1832)");
checkC++;
break;
case "pubDate":
- assertEquals("type:date", field.at("/type").asText());
+ assertEquals(field.at("/type").asText(), "type:date");
assertEquals(1982, field.at("/value").asInt());
checkC++;
break;
- };
- };
+ }
+ ;
+ }
+ ;
assertEquals(5, checkC);
- };
-
- @Test
- public void testSearchWithoutVersion () throws KustvaktException {
- Response response = target().path("api").path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .request()
- .accept(MediaType.APPLICATION_JSON).get();
- assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
- URI location = response.getLocation();
- assertEquals("/api/v1.0/search", location.getPath());
}
@Test
- public void testSearchWrongVersion () throws KustvaktException {
- Response response = target().path("api").path("v0.2")
- .path("search").queryParam("q", "[orth=der]")
- .queryParam("ql", "poliqarp")
- .request()
- .accept(MediaType.APPLICATION_JSON)
- .get();
+ public void testSearchWithoutVersion() throws KustvaktException {
+ Response response = target().path("api").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
URI location = response.getLocation();
- assertEquals("/api/v1.0/search", location.getPath());
+ assertEquals(location.getPath(), "/api/v1.0/search");
}
@Test
- public void testSearchWithIP () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
- .request()
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
+ public void testSearchWrongVersion() throws KustvaktException {
+ Response response = target().path("api").path("v0.2").path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").request().accept(MediaType.APPLICATION_JSON).get();
+ assertEquals(HttpStatus.PERMANENT_REDIRECT_308, response.getStatus());
+ URI location = response.getLocation();
+ assertEquals(location.getPath(), "/api/v1.0/search");
+ }
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchWithIP() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/collection").isMissingNode());
}
@Test
- public void testSearchWithAuthorizationHeader () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Wasser").queryParam("ql", "poliqarp")
- .request()
- .header(Attributes.AUTHORIZATION, HttpAuthorizationHandler
- .createBasicAuthorizationHeaderValue("test", "pwd"))
- .header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32")
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithAuthorizationHeader() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Wasser").queryParam("ql", "poliqarp").request().header(Attributes.AUTHORIZATION, HttpAuthorizationHandler.createBasicAuthorizationHeaderValue("test", "pwd")).header(HttpHeaders.X_FORWARDED_FOR, "149.27.0.32").get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertTrue(node.at("/collection").isMissingNode());
}
-
+
@Test
- public void testSearchPublicMetadata () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadata() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
-
assertTrue(node.at("/matches/0/snippet").isMissingNode());
}
-
- @Test
- public void testSearchPublicMetadataWithCustomFields () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("fields", "author,title")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- String entity = response.readEntity(String.class);
- JsonNode node = JsonUtils.readTree(entity);
-
- assertTrue(node.at("/matches/0/snippet").isMissingNode());
- assertEquals("Goethe, Johann Wolfgang von",
- node.at("/matches/0/author").asText());
- assertEquals("Italienische Reise",
- node.at("/matches/0/title").asText());
-// assertEquals(3, node.at("/matches/0").size());
- }
-
- @Test
- public void testSearchPublicMetadataWithNonPublicField () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "Sonne").queryParam("ql", "poliqarp")
- .queryParam("fields", "author,title,snippet")
- .queryParam("access-rewrite-disabled", "true")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
- String entity = response.readEntity(String.class);
- JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED,
- node.at("/warnings/0/0").asInt());
- assertEquals("The requested non public fields are ignored",
- node.at("/warnings/0/1").asText());
- assertEquals("snippet",
- node.at("/warnings/0/2").asText());
- }
-
@Test
- public void testSearchWithInvalidPage () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=die]").queryParam("ql", "poliqarp")
- .queryParam("page", "0")
- .request()
- .get();
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ public void testSearchPublicMetadataWithCustomFields() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ String entity = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(entity);
+ assertTrue(node.at("/matches/0/snippet").isMissingNode());
+ assertEquals(node.at("/matches/0/author").asText(), "Goethe, Johann Wolfgang von");
+ assertEquals(node.at("/matches/0/title").asText(), "Italienische Reise");
+ // assertEquals(3, node.at("/matches/0").size());
+ }
+
+ @Test
+ public void testSearchPublicMetadataWithNonPublicField() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "Sonne").queryParam("ql", "poliqarp").queryParam("fields", "author,title,snippet").queryParam("access-rewrite-disabled", "true").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ String entity = response.readEntity(String.class);
+ JsonNode node = JsonUtils.readTree(entity);
+ assertEquals(StatusCodes.NON_PUBLIC_FIELD_IGNORED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "The requested non public fields are ignored");
+ assertEquals(node.at("/warnings/0/2").asText(), "snippet");
+ }
+
+ @Test
+ public void testSearchWithInvalidPage() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=die]").queryParam("ql", "poliqarp").queryParam("page", "0").request().get();
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.INVALID_ARGUMENT, node.at("/errors/0/0").asInt());
- assertEquals("page must start from 1",node.at("/errors/0/1").asText());
+ assertEquals(node.at("/errors/0/1").asText(), "page must start from 1");
}
-
+
@Test
- public void testCloseIndex () throws IOException, KustvaktException {
+ public void testCloseIndex() throws IOException, KustvaktException {
searchKrill.getStatistics(null);
assertEquals(true, searchKrill.getIndex().isReaderOpen());
-
Form form = new Form();
form.param("token", "secret");
-
- Response response = target().path(API_VERSION).path("index")
- .path("close")
- .request()
- .post(Entity.form(form));
-
+ Response response = target().path(API_VERSION).path("index").path("close").request().post(Entity.form(form));
assertEquals(HttpStatus.OK_200, response.getStatus());
assertEquals(false, searchKrill.getIndex().isReaderOpen());
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
index 80c52ca..bc45ad0 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchPipeTest.java
@@ -1,7 +1,7 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
@@ -17,13 +17,12 @@
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Header;
-
import com.fasterxml.jackson.databind.JsonNode;
import javax.ws.rs.core.Response;
@@ -37,344 +36,171 @@
public class LiteSearchPipeTest extends LiteJerseyTest {
private ClientAndServer mockServer;
+
private MockServerClient mockClient;
private int port = 6070;
+
private String pipeJson, pipeWithParamJson;
- private String glemmUri = "http://localhost:"+port+"/glemm";
- public LiteSearchPipeTest () throws IOException{
- pipeJson = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "pipe-output/test-pipes.jsonld"),
- StandardCharsets.UTF_8);
+ private String glemmUri = "http://localhost:" + port + "/glemm";
- pipeWithParamJson = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "pipe-output/with-param.jsonld"),
- StandardCharsets.UTF_8);
+ public LiteSearchPipeTest() throws IOException {
+ pipeJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/test-pipes.jsonld"), StandardCharsets.UTF_8);
+ pipeWithParamJson = IOUtils.toString(ClassLoader.getSystemResourceAsStream("pipe-output/with-param.jsonld"), StandardCharsets.UTF_8);
}
- @Before
- public void startMockServer () {
+ @BeforeEach
+ public void startMockServer() {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
- @After
- public void stopMockServer () {
+ @AfterEach
+ public void stopMockServer() {
mockServer.stop();
}
@Test
- public void testMockServer () throws IOException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/test")
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody("{test}").withStatusCode(200));
-
- URL url = new URL("http://localhost:"+port+"/test");
+ public void testMockServer() throws IOException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/test").withHeader(new Header("Content-Type", "application/json; charset=utf-8"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody("{test}").withStatusCode(200));
+ URL url = new URL("http://localhost:" + port + "/test");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
- connection.setRequestProperty("Content-Type",
- "application/json; charset=UTF-8");
+ connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
-
String json = "{\"name\" : \"dory\"}";
try (OutputStream os = connection.getOutputStream()) {
byte[] input = json.getBytes("utf-8");
os.write(input, 0, input.length);
}
-
assertEquals(200, connection.getResponseCode());
-
- BufferedReader br = new BufferedReader(
- new InputStreamReader(connection.getInputStream(), "utf-8"));
- assertEquals("{test}", br.readLine());
-
+ BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
+ assertEquals(br.readLine(), "{test}");
}
@Test
- public void testSearchWithPipes ()
- throws IOException, KustvaktException, URISyntaxException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithPipes() throws IOException, KustvaktException, URISyntaxException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
-
node = node.at("/query/wrap/rewrites");
assertEquals(2, node.size());
- assertEquals("Glemm", node.at("/0/src").asText());
- assertEquals("operation:override", node.at("/0/operation").asText());
- assertEquals("key", node.at("/0/scope").asText());
-
- assertEquals("Kustvakt", node.at("/1/src").asText());
- assertEquals("operation:injection", node.at("/1/operation").asText());
- assertEquals("foundry", node.at("/1/scope").asText());
+ assertEquals(node.at("/0/src").asText(), "Glemm");
+ assertEquals(node.at("/0/operation").asText(), "operation:override");
+ assertEquals(node.at("/0/scope").asText(), "key");
+ assertEquals(node.at("/1/src").asText(), "Kustvakt");
+ assertEquals(node.at("/1/operation").asText(), "operation:injection");
+ assertEquals(node.at("/1/scope").asText(), "foundry");
}
@Test
- public void testSearchWithUrlEncodedPipes ()
- throws IOException, KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
+ public void testSearchWithUrlEncodedPipes() throws IOException, KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
glemmUri = URLEncoder.encode(glemmUri, "utf-8");
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri)
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri).request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithMultiplePipes () throws KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withQueryStringParameter("param").withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeWithParamJson).withStatusCode(200));
-
+ public void testSearchWithMultiplePipes() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withQueryStringParameter("param").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeWithParamJson).withStatusCode(200));
String glemmUri2 = glemmUri + "?param=blah";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri + "," + glemmUri2)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + "," + glemmUri2).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(3, node.at("/query/wrap/key").size());
}
@Test
- public void testSearchWithUnknownURL ()
- throws IOException, KustvaktException {
- String url =
- target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", url)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithUnknownURL() throws IOException, KustvaktException {
+ String url = target().getUri().toString() + API_VERSION + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
-
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("404 Not Found", node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "404 Not Found");
}
@Test
- public void testSearchWithUnknownHost () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", "http://glemm")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithUnknownHost() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://glemm").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("glemm", node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "glemm");
}
@Test
- public void testSearchUnsupportedMediaType () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/non-json-pipe"))
- .respond(response().withStatusCode(415));
-
- String pipeUri = "http://localhost:"+port+"/non-json-pipe";
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchUnsupportedMediaType() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/non-json-pipe")).respond(response().withStatusCode(415));
+ String pipeUri = "http://localhost:" + port + "/non-json-pipe";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
- assertEquals("415 Unsupported Media Type",
- node.at("/warnings/0/3").asText());
+ assertEquals(node.at("/warnings/0/3").asText(), "415 Unsupported Media Type");
}
@Test
- public void testSearchWithMultiplePipeWarnings () throws KustvaktException {
- String url =
- target().getUri().toString() + API_VERSION + "/test/tralala";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", url + "," + "http://glemm")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithMultiplePipeWarnings() throws KustvaktException {
+ String url = target().getUri().toString() + API_VERSION + "/test/tralala";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", url + "," + "http://glemm").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2, node.at("/warnings").size());
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
assertEquals(url, node.at("/warnings/0/2").asText());
- assertEquals("404 Not Found", node.at("/warnings/0/3").asText());
-
+ assertEquals(node.at("/warnings/0/3").asText(), "404 Not Found");
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/1/0").asInt());
- assertEquals("http://glemm", node.at("/warnings/1/2").asText());
- assertEquals("glemm", node.at("/warnings/1/3").asText());
-
+ assertEquals(node.at("/warnings/1/2").asText(), "http://glemm");
+ assertEquals(node.at("/warnings/1/3").asText(), "glemm");
}
@Test
- public void testSearchWithInvalidJsonResponse () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/invalid-response")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response().withBody("{blah:}").withStatusCode(200)
- .withHeaders(new Header("Content-Type",
- "application/json; charset=utf-8")));
-
- String pipeUri = "http://localhost:"+port+"/invalid-response";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchWithInvalidJsonResponse() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/invalid-response").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("{blah:}").withStatusCode(200).withHeaders(new Header("Content-Type", "application/json; charset=utf-8")));
+ String pipeUri = "http://localhost:" + port + "/invalid-response";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithPlainTextResponse () throws KustvaktException {
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/plain-text")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response().withBody("blah").withStatusCode(200));
-
- String pipeUri = "http://localhost:"+port+"/plain-text";
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", pipeUri)
- .request()
- .get();
-
+ public void testSearchWithPlainTextResponse() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/plain-text").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withBody("blah").withStatusCode(200));
+ String pipeUri = "http://localhost:" + port + "/plain-text";
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", pipeUri).request().get();
String entity = response.readEntity(String.class);
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
}
@Test
- public void testSearchWithMultipleAndUnknownPipes ()
- throws KustvaktException {
-
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/glemm")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(pipeJson).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", "http://unknown" + "," + glemmUri)
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ public void testSearchWithMultipleAndUnknownPipes() throws KustvaktException {
+ mockClient.reset().when(request().withMethod("POST").withPath("/glemm").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(pipeJson).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", "http://unknown" + "," + glemmUri).request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
assertEquals(2, node.at("/query/wrap/key").size());
assertTrue(node.at("/warnings").isMissingNode());
-
- response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("pipes", glemmUri + ",http://unknown")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("pipes", glemmUri + ",http://unknown").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
entity = response.readEntity(String.class);
node = JsonUtils.readTree(entity);
assertEquals(StatusCodes.PIPE_FAILED, node.at("/warnings/0/0").asInt());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
index 5a521f8..57d1a89 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteSearchTokenSnippetTest.java
@@ -1,11 +1,10 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
import javax.ws.rs.core.Response;
@@ -16,68 +15,42 @@
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.utils.JsonUtils;
-public class LiteSearchTokenSnippetTest extends LiteJerseyTest{
+public class LiteSearchTokenSnippetTest extends LiteJerseyTest {
@Test
- public void testSearchWithTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("show-tokens", "true")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testSearchWithTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertTrue(node.at("/matches/0/hasSnippet").asBoolean());
assertTrue(node.at("/matches/0/hasTokens").asBoolean());
- assertTrue(node.at("/matches/0/tokens/left").size()>0);
- assertTrue(node.at("/matches/0/tokens/right").size()>0);
+ assertTrue(node.at("/matches/0/tokens/left").size() > 0);
+ assertTrue(node.at("/matches/0/tokens/right").size() > 0);
assertEquals(1, node.at("/matches/0/tokens/match").size());
}
-
- @Test
- public void testSearchWithoutTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("show-tokens", "false")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchWithoutTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("show-tokens", "false").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertTrue(node.at("/matches/0/hasSnippet").asBoolean());
assertFalse(node.at("/matches/0/hasTokens").asBoolean());
assertTrue(node.at("/matches/0/tokens").isMissingNode());
}
-
- @Test
- public void testSearchPublicMetadataWithTokens () throws KustvaktException {
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=das]").queryParam("ql", "poliqarp")
- .queryParam("access-rewrite-disabled", "true")
- .queryParam("show-tokens", "true")
- .queryParam("context", "sentence").queryParam("count", "13")
- .request()
- .get();
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testSearchPublicMetadataWithTokens() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=das]").queryParam("ql", "poliqarp").queryParam("access-rewrite-disabled", "true").queryParam("show-tokens", "true").queryParam("context", "sentence").queryParam("count", "13").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
-
assertFalse(node.at("/matches/0/hasSnippet").asBoolean());
assertFalse(node.at("/matches/0/hasTokens").asBoolean());
assertTrue(node.at("/matches/0/snippet").isMissingNode());
assertTrue(node.at("/matches/0/tokens").isMissingNode());
-
assertEquals(StatusCodes.NOT_ALLOWED, node.at("/warnings/0/0").asInt());
}
}
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
index b116e1e..c48e58e 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/LiteStatisticControllerTest.java
@@ -1,116 +1,77 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.IOException;
-
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
-import org.junit.Test;
-
+import org.junit.jupiter.api.Test;
import com.fasterxml.jackson.databind.JsonNode;
-
import de.ids_mannheim.korap.config.LiteJerseyTest;
import de.ids_mannheim.korap.exceptions.KustvaktException;
import de.ids_mannheim.korap.exceptions.StatusCodes;
import de.ids_mannheim.korap.utils.JsonUtils;
-public class LiteStatisticControllerTest extends LiteJerseyTest{
+public class LiteStatisticControllerTest extends LiteJerseyTest {
@Test
- public void testStatisticsWithCq () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
-
+ public void testStatisticsWithCq() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
-
+
@Test
- public void testStatisticsWithCqAndCorpusQuery () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("cq", "textType=Abhandlung & corpusSigle=GOE")
- .queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithCqAndCorpusQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("cq", "textType=Abhandlung & corpusSigle=GOE").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(2, node.at("/documents").asInt());
assertEquals(138180, node.at("/tokens").asInt());
assertEquals(5687, node.at("/sentences").asInt());
assertEquals(258, node.at("/paragraphs").asInt());
-
assertTrue(node.at("/warnings").isMissingNode());
}
-
+
@Test
- public void testStatisticsWithCorpusQuery () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testStatisticsWithCorpusQuery() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "textType=Autobiographie & corpusSigle=GOE").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(9, node.at("/documents").asInt());
assertEquals(527662, node.at("/tokens").asInt());
assertEquals(19387, node.at("/sentences").asInt());
assertEquals(514, node.at("/paragraphs").asInt());
-
- assertEquals(StatusCodes.DEPRECATED,
- node.at("/warnings/0/0").asInt());
- assertEquals("Parameter corpusQuery is deprecated in favor of cq.",
- node.at("/warnings/0/1").asText());
+ assertEquals(StatusCodes.DEPRECATED, node.at("/warnings/0/0").asInt());
+ assertEquals(node.at("/warnings/0/1").asText(), "Parameter corpusQuery is deprecated in favor of cq.");
}
@Test
- public void testEmptyStatistics () throws KustvaktException{
- Response response = target().path(API_VERSION)
- .path("statistics")
- .queryParam("corpusQuery", "")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testEmptyStatistics() throws KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").queryParam("corpusQuery", "").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String query = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(query);
assertEquals(11, node.at("/documents").asInt());
assertEquals(665842, node.at("/tokens").asInt());
assertEquals(25074, node.at("/sentences").asInt());
assertEquals(772, node.at("/paragraphs").asInt());
-
- response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .method("GET");
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ response = target().path(API_VERSION).path("statistics").request().method("GET");
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
query = response.readEntity(String.class);
node = JsonUtils.readTree(query);
assertEquals(11, node.at("/documents").asInt());
@@ -118,85 +79,45 @@
assertEquals(25074, node.at("/sentences").asInt());
assertEquals(772, node.at("/paragraphs").asInt());
}
-
+
@Test
- public void testGetStatisticsWithKoralQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{ \"collection\" : {\"@type\": "
- + "\"koral:doc\", \"key\": \"availability\", \"match\": "
- + "\"match:eq\", \"type\": \"type:regex\", \"value\": "
- + "\"CC-BY.*\"} }"));
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
+ public void testGetStatisticsWithKoralQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : {\"@type\": " + "\"koral:doc\", \"key\": \"availability\", \"match\": " + "\"match:eq\", \"type\": \"type:regex\", \"value\": " + "\"CC-BY.*\"} }"));
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
-
- assertEquals(
- "Wes8Bd4h1OypPqbWF5njeQ==",
- response.getHeaders().getFirst("X-Index-Revision")
- );
-
+ assertEquals(response.getHeaders().getFirst("X-Index-Revision"), "Wes8Bd4h1OypPqbWF5njeQ==");
JsonNode node = JsonUtils.readTree(ent);
assertEquals(2, node.at("/documents").asInt());
assertEquals(72770, node.at("/tokens").asInt());
assertEquals(2985, node.at("/sentences").asInt());
assertEquals(128, node.at("/paragraphs").asInt());
}
-
- @Test
- public void testGetStatisticsWithEmptyCollection ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{}"));
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testGetStatisticsWithEmptyCollection() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{}"));
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(node.at("/errors/0/0").asInt(),
- de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
- assertEquals(node.at("/errors/0/1").asText(),
- "Collection is not found");
+ assertEquals(node.at("/errors/0/0").asInt(), de.ids_mannheim.korap.util.StatusCodes.MISSING_COLLECTION);
+ assertEquals(node.at("/errors/0/1").asText(), "Collection is not found");
}
-
- @Test
- public void testGetStatisticsWithIncorrectJson ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON)
- .post(Entity.json("{ \"collection\" : }"));
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ @Test
+ public void testGetStatisticsWithIncorrectJson() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON).post(Entity.json("{ \"collection\" : }"));
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
String ent = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(ent);
- assertEquals(StatusCodes.DESERIALIZATION_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals("Failed deserializing json object: { \"collection\" : }",
- node.at("/errors/0/1").asText());
+ assertEquals(StatusCodes.DESERIALIZATION_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(node.at("/errors/0/1").asText(), "Failed deserializing json object: { \"collection\" : }");
}
-
+
@Test
- public void testGetStatisticsWithoutKoralQuery ()
- throws IOException, KustvaktException {
- Response response = target().path(API_VERSION)
- .path("statistics")
- .request()
- .post(Entity.json(""));
-
+ public void testGetStatisticsWithoutKoralQuery() throws IOException, KustvaktException {
+ Response response = target().path(API_VERSION).path("statistics").request().post(Entity.json(""));
String ent = response.readEntity(String.class);
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
JsonNode node = JsonUtils.readTree(ent);
assertEquals(11, node.at("/documents").asInt());
assertEquals(665842, node.at("/tokens").asInt());
diff --git a/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java b/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
index f90dde0..5590183 100644
--- a/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
+++ b/full/src/test/java/de/ids_mannheim/korap/web/lite/SearchNetworkEndpointTest.java
@@ -1,6 +1,6 @@
package de.ids_mannheim.korap.web.lite;
-import static org.junit.Assert.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockserver.integration.ClientAndServer.startClientAndServer;
import static org.mockserver.model.HttpRequest.request;
import static org.mockserver.model.HttpResponse.response;
@@ -10,15 +10,15 @@
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.IOUtils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.integration.ClientAndServer;
import org.mockserver.model.Header;
import org.springframework.beans.factory.annotation.Autowired;
-
import com.fasterxml.jackson.databind.JsonNode;
+
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
@@ -34,97 +34,58 @@
private KustvaktConfiguration config;
private ClientAndServer mockServer;
+
private MockServerClient mockClient;
private int port = 6080;
- private String searchResult;
- private String endpointURL = "http://localhost:"+port+"/searchEndpoint";
- public SearchNetworkEndpointTest () throws IOException {
- searchResult = IOUtils.toString(
- ClassLoader.getSystemResourceAsStream(
- "network-output/search-result.jsonld"),
- StandardCharsets.UTF_8);
+ private String searchResult;
+
+ private String endpointURL = "http://localhost:" + port + "/searchEndpoint";
+
+ public SearchNetworkEndpointTest() throws IOException {
+ searchResult = IOUtils.toString(ClassLoader.getSystemResourceAsStream("network-output/search-result.jsonld"), StandardCharsets.UTF_8);
}
-
- @Before
- public void startMockServer () {
+ @BeforeEach
+ public void startMockServer() {
mockServer = startClientAndServer(port);
mockClient = new MockServerClient("localhost", mockServer.getPort());
}
-
- @After
- public void stopMockServer () {
+ @AfterEach
+ public void stopMockServer() {
mockServer.stop();
}
-
@Test
- public void testSearchNetwork ()
- throws IOException, KustvaktException, URISyntaxException {
+ public void testSearchNetwork() throws IOException, KustvaktException, URISyntaxException {
config.setNetworkEndpointURL(endpointURL);
- mockClient.reset()
- .when(request().withMethod("POST").withPath("/searchEndpoint")
- .withHeaders(
- new Header("Content-Type",
- "application/json; charset=utf-8"),
- new Header("Accept", "application/json")))
- .respond(response()
- .withHeader(new Header("Content-Type",
- "application/json; charset=utf-8"))
- .withBody(searchResult).withStatusCode(200));
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
-
- assertEquals(Status.OK.getStatusCode(),
- response.getStatus());
-
+ mockClient.reset().when(request().withMethod("POST").withPath("/searchEndpoint").withHeaders(new Header("Content-Type", "application/json; charset=utf-8"), new Header("Accept", "application/json"))).respond(response().withHeader(new Header("Content-Type", "application/json; charset=utf-8")).withBody(searchResult).withStatusCode(200));
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
+ assertEquals(Status.OK.getStatusCode(), response.getStatus());
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
-
assertEquals(2, node.at("/matches").size());
}
-
@Test
- public void testSearchWithUnknownURL ()
- throws IOException, KustvaktException {
+ public void testSearchWithUnknownURL() throws IOException, KustvaktException {
config.setNetworkEndpointURL("http://localhost:1040/search");
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
-
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-
- @Test
- public void testSearchWithUnknownHost () throws KustvaktException {
- config.setNetworkEndpointURL("http://search.com");
-
- Response response = target().path(API_VERSION).path("search")
- .queryParam("q", "[orth=der]").queryParam("ql", "poliqarp")
- .queryParam("engine", "network")
- .request()
- .get();
+ @Test
+ public void testSearchWithUnknownHost() throws KustvaktException {
+ config.setNetworkEndpointURL("http://search.com");
+ Response response = target().path(API_VERSION).path("search").queryParam("q", "[orth=der]").queryParam("ql", "poliqarp").queryParam("engine", "network").request().get();
String entity = response.readEntity(String.class);
JsonNode node = JsonUtils.readTree(entity);
- assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED,
- node.at("/errors/0/0").asInt());
- assertEquals(Status.BAD_REQUEST.getStatusCode(),
- response.getStatus());
+ assertEquals(StatusCodes.SEARCH_NETWORK_ENDPOINT_FAILED, node.at("/errors/0/0").asInt());
+ assertEquals(Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
}
diff --git a/full/src/test/resources/junit-platform.properties b/full/src/test/resources/junit-platform.properties
new file mode 100644
index 0000000..f4cf442
--- /dev/null
+++ b/full/src/test/resources/junit-platform.properties
@@ -0,0 +1,4 @@
+junit.jupiter.testclass.order.default = org.junit.jupiter.api.ClassOrderer$OrderAnnotation
+junit.jupiter.execution.parallel.enabled = true
+
+