repo stringclasses 1k
values | file_url stringlengths 96 373 | file_path stringlengths 11 294 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 6
values | commit_sha stringclasses 1k
values | retrieved_at stringdate 2026-01-04 14:45:56 2026-01-04 18:30:23 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/test/java/org/smartdata/integration/util/RetryTask.java | smart-integration/src/test/java/org/smartdata/integration/util/RetryTask.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.util;
public interface RetryTask {
boolean retry();
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/test/java/org/smartdata/integration/util/Util.java | smart-integration/src/test/java/org/smartdata/integration/util/Util.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.util;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.apache.commons.lang.StringUtils;
import org.smartdata.agent.SmartAgent;
import org.smartdata.integration.rest.RestApiBase;
import org.smartdata.server.SmartDaemon;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static io.restassured.path.json.JsonPath.with;
public class Util {
public static void waitSlaveServerAvailable() throws InterruptedException {
Util.retryUntil(new RetryTask() {
@Override
public boolean retry() {
Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/servers");
List<String> ids = with(response.asString()).get("body.id");
return ids.size() > 0;
}
}, 15);
}
public static void waitSlaveServersDown() throws InterruptedException {
Util.retryUntil(new RetryTask() {
@Override
public boolean retry() {
Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/servers");
List<String> ids = with(response.asString()).get("body.id");
return ids.size() == 0;
}
}, 15);
}
public static void waitAgentAvailable() throws InterruptedException {
Util.retryUntil(new RetryTask() {
@Override
public boolean retry() {
Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/agents");
List<String> ids = with(response.asString()).get("body.id");
return ids.size() > 0;
}
}, 15);
}
public static void waitAgentsDown() throws InterruptedException {
Util.retryUntil(new RetryTask() {
@Override
public boolean retry() {
Response response = RestAssured.get(RestApiBase.SYSTEMROOT + "/agents");
List<String> ids = with(response.asString()).get("body.id");
return ids.size() == 0;
}
}, 15);
}
public static void retryUntil(RetryTask retryTask, int maxRetries) throws InterruptedException {
retryUntil(retryTask, maxRetries, 1000);
}
public static void retryUntil(RetryTask retryTask, int maxRetries, long interval)
throws InterruptedException {
boolean met = false;
int retries = 0;
while (!met && retries < maxRetries) {
met = retryTask.retry();
retries += 1;
if (!met) {
Thread.sleep(interval);
}
}
if (!met) {
throw new RuntimeException("Failed after retry " + maxRetries + "times.");
}
}
public static Process startNewServer() throws IOException {
return Util.buildProcess(
System.getProperty("java.class.path").split(java.io.File.pathSeparator),
SmartDaemon.class.getCanonicalName(),
new String[0]);
}
public static Process startNewAgent() throws IOException {
return Util.buildProcess(
System.getProperty("java.class.path").split(java.io.File.pathSeparator),
SmartAgent.class.getCanonicalName(),
new String[0]);
}
public static Process buildProcess(
String[] options, String[] classPath, String mainClass, String[] arguments)
throws IOException {
String java = System.getProperty("java.home") + "/bin/java";
List<String> commands = new ArrayList<>();
commands.add(java);
commands.addAll(Arrays.asList(options));
commands.add("-cp");
commands.add(StringUtils.join(classPath, File.pathSeparator));
commands.add(mainClass);
commands.addAll(Arrays.asList(arguments));
return new ProcessBuilder(commands).start();
}
public static Process buildProcess(String mainClass, String[] arguments) throws IOException {
return buildProcess(new String[0], mainClass, arguments);
}
public static Process buildProcess(String[] classPath, String mainClass, String[] arguments)
throws IOException {
return buildProcess(new String[0], classPath, mainClass, arguments);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/test/java/org/smartdata/integration/cluster/SmartCluster.java | smart-integration/src/test/java/org/smartdata/integration/cluster/SmartCluster.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.cluster;
import org.smartdata.conf.SmartConf;
/**
* Interface for a Smart cluster.
*/
public interface SmartCluster {
/**
* Set up a cluster or attach to a specific cluster.
*/
void setUp() throws Exception;
/**
* Get the configuration of the cluster.
* @return
*/
SmartConf getConf();
/**
* Cleaning-up work to quit the cluster.
*/
void cleanUp() throws Exception;
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/test/java/org/smartdata/integration/cluster/SmartMiniCluster.java | smart-integration/src/test/java/org/smartdata/integration/cluster/SmartMiniCluster.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.cluster;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.DFSUtil;
import org.apache.hadoop.hdfs.MiniDFSCluster;
import org.apache.hadoop.hdfs.server.balancer.TestBalancer;
import org.smartdata.conf.SmartConf;
import org.smartdata.conf.SmartConfKeys;
import org.smartdata.hdfs.MiniClusterFactory;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import static org.apache.hadoop.hdfs.DFSConfigKeys.DFS_NAMENODE_HTTP_ADDRESS_KEY;
/**
* A MiniCluster for integration test.
*/
public class SmartMiniCluster implements SmartCluster {
private SmartConf conf;
private MiniDFSCluster cluster;
private static final int DEFAULT_BLOCK_SIZE = 100;
static {
TestBalancer.initTestSetup();
}
private void initConf(Configuration conf) {
conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, DEFAULT_BLOCK_SIZE);
conf.setInt(DFSConfigKeys.DFS_BYTES_PER_CHECKSUM_KEY, DEFAULT_BLOCK_SIZE);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setLong(DFSConfigKeys.DFS_BALANCER_MOVEDWINWIDTH_KEY, 2000L);
}
@Override
public void setUp() throws Exception {
conf = new SmartConf();
initConf(conf);
cluster = MiniClusterFactory.get().createWithStorages(3, conf);
cluster.waitActive();
Collection<URI> namenodes = DFSUtil.getInternalNsRpcUris(conf);
List<URI> uriList = new ArrayList<>(namenodes);
conf.set(DFS_NAMENODE_HTTP_ADDRESS_KEY, uriList.get(0).toString());
conf.set(SmartConfKeys.SMART_DFS_NAMENODE_RPCSERVER_KEY,
uriList.get(0).toString());
}
@Override
public SmartConf getConf() {
return conf;
}
@Override
public void cleanUp() {
if (cluster != null) {
cluster.shutdown();
}
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/ActionRestApi.java | smart-integration/src/main/java/org/smartdata/integration/rest/ActionRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.hamcrest.Matchers;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ActionRestApi extends RestApiBase {
/**
* Submit an action using action type and arguments.
* @param actionType
* @param args
* @return
*/
public static Long submitAction(String actionType, String args) {
return CmdletRestApi.submitCmdlet(actionType + " " + args);
}
/**
* Get aids of a cmdlet.
* @param cid
* @return
*/
public static List<Long> getActionIds(long cid) {
Response cmdletInfo = RestAssured.get(CMDLETROOT + "/" + cid + "/info");
cmdletInfo.then().body("status", Matchers.equalTo("OK"));
JsonPath cmdletInfoPath = new JsonPath(cmdletInfo.asString());
List<Long> ret = new ArrayList<>();
for (Object obj: (List) cmdletInfoPath.getMap("body").get("aids")) {
ret.add(CovUtil.getLong(obj));
}
return ret;
}
public static Map getActionInfoMap(long aid) {
Response actionInfo = RestAssured.get(ACTIONROOT + "/" + aid + "/info");
actionInfo.then().body("status", Matchers.equalTo("OK"));
JsonPath actionInfoPath = new JsonPath(actionInfo.asString());
Map actionInfoMap = actionInfoPath.getMap("body");
return actionInfoMap;
}
/**
* Get action info of an action.
* @param aid
* @return
*/
public static JsonPath getActionInfo(long aid) {
Response resp = RestAssured.get(ACTIONROOT + "/" + aid + "/info");
resp.then().body("status", Matchers.equalTo("OK"));
return resp.jsonPath().setRoot("body");
}
/**
* Get list of action names supported in SmartServer.
* @return
*/
public static List<String> getActionsSupported() {
Response response = RestAssured.get(ACTIONROOT + "/registry/list");
response.then().body("status", Matchers.equalTo("OK"));
return response.jsonPath().getList("body");
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/RuleRestApi.java | smart-integration/src/main/java/org/smartdata/integration/rest/RuleRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.hamcrest.Matchers;
import static org.hamcrest.Matchers.equalTo;
public class RuleRestApi extends RestApiBase {
public static long submitRule(String ruleText) {
Response res = RestAssured.with()
.body("ruleText=" + ruleText).post(RULEROOT + "/add");
res.then().body("status", equalTo("CREATED"));
return res.jsonPath().getLong("body");
}
public static void startRule(long ruleId) {
RestAssured.post(RULEROOT + "/" + ruleId + "/start").then()
.body("status", equalTo("OK"));
}
public static JsonPath getRuleInfo(long ruleId) {
Response cmdletInfo = RestAssured.get(RULEROOT + "/" + ruleId + "/info");
cmdletInfo.then().body("status", Matchers.equalTo("OK"));
JsonPath path = cmdletInfo.jsonPath().setRoot("body");
return path;
}
/**
* Wait until the specified rule generates one cmdlet.
* @param ruleId
* @param secToWait
* @return
*/
public static boolean waitRuleTriggered(long ruleId, int secToWait) {
do {
JsonPath pa = getRuleInfo(ruleId);
// System.out.println("numChecked = " + pa.getLong("numChecked")
// + ", numCmdsGen = " + pa.getLong("numCmdsGen"));
if (pa.getLong("numCmdsGen") > 0) {
return true;
}
secToWait--;
if (secToWait < 0) {
break;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
// ignore
}
} while (true);
return false;
}
public static boolean waitRuleTriggered(long ruleId) {
return waitRuleTriggered(ruleId, Integer.MAX_VALUE);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/ClusterRestApi.java | smart-integration/src/main/java/org/smartdata/integration/rest/ClusterRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import java.util.List;
import static org.hamcrest.Matchers.equalTo;
public class ClusterRestApi extends RuleRestApi {
public static JsonPath getCachedFiles() {
Response resp = RestAssured.get(PRIMCLUSTERROOT + "/cachedfiles");
resp.then().body("status", equalTo("OK"));
return resp.jsonPath().setRoot("body");
}
public static JsonPath getFileInfo(String path) {
Response resp = RestAssured.with().body(path).get(PRIMCLUSTERROOT + "/fileinfo");
resp.then().body("status", equalTo("OK"));
return resp.jsonPath().setRoot("body");
}
/**
* Get list of file paths that been cached.
* @return
*/
public static List<String> getCachedFilePaths() {
return getCachedFiles().getList("path", String.class);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/CmdletRestApi.java | smart-integration/src/main/java/org/smartdata/integration/rest/CmdletRestApi.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import org.hamcrest.Matchers;
import java.util.List;
public class CmdletRestApi extends RestApiBase {
/**
* Submit an cmdlet.
* @param cmdString
* @return cmdlet id if success
*/
public static Long submitCmdlet(String cmdString) {
Response action = RestAssured.with().body(cmdString).post(CMDLETROOT + "/submit");
//Response action = RestAssured.withArgs(cmdString).post(CMDLETROOT + "/submit");
action.then().body("status", Matchers.equalTo("CREATED"));
return new JsonPath(action.asString()).getLong("body");
}
public static boolean waitCmdletComplete(long cmdletId) {
return waitCmdletComplete(cmdletId, Integer.MAX_VALUE);
}
/**
* Wait until the specified cmdlet finishes.
* @param cmdletId
* @param secToWait
* @return
*/
public static boolean waitCmdletComplete(long cmdletId, int secToWait) {
do {
JsonPath path = getCmdletInfo(cmdletId);
if (path.get("state").equals("DONE")) {
return true;
}
secToWait--;
if (secToWait < 0) {
break;
}
try {
Thread.sleep(1000);
} catch (Exception e) {
// ignore
}
} while (true);
return false;
}
public static JsonPath getCmdletInfo(long cmdletId) {
Response cmdletInfo = RestAssured.get(CMDLETROOT + "/" + cmdletId + "/info");
cmdletInfo.then().body("status", Matchers.equalTo("OK"));
JsonPath path = cmdletInfo.jsonPath().setRoot("body");
return path;
}
public static List<Long> getCmdletActionIds(long cmdletId) {
return getCmdletInfo(cmdletId).getList("aids", Long.class);
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/CovUtil.java | smart-integration/src/main/java/org/smartdata/integration/rest/CovUtil.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
public class CovUtil {
public static Long getLong(Object o) {
if (o instanceof Integer) {
return new Long((Integer) o);
}
return (Long) o;
}
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
Intel-bigdata/SSM | https://github.com/Intel-bigdata/SSM/blob/e0c90f054687a18c4e095547ac5e31b8b313b3ef/smart-integration/src/main/java/org/smartdata/integration/rest/RestApiBase.java | smart-integration/src/main/java/org/smartdata/integration/rest/RestApiBase.java | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.smartdata.integration.rest;
public class RestApiBase {
public static final String ROOT = "/smart/api/v1";
public static final String RULEROOT = ROOT + "/rules";
public static final String CMDLETROOT = ROOT + "/cmdlets";
public static final String ACTIONROOT = ROOT + "/actions";
public static final String CLUSTERROOT = ROOT + "/cluster";
public static final String SYSTEMROOT = ROOT + "/system";
public static final String CONFROOT = ROOT + "/conf";
public static final String PRIMCLUSTERROOT = ROOT + "/cluster/primary";
}
| java | Apache-2.0 | e0c90f054687a18c4e095547ac5e31b8b313b3ef | 2026-01-05T02:41:11.405497Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java | spring-data-mock-sample-mongo/src/test/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreServiceTest.java | package com.mmnaseri.utils.samples.spring.data.mongo.service.impl;
import com.mmnaseri.utils.samples.spring.data.mongo.model.Store;
import com.mmnaseri.utils.samples.spring.data.mongo.repository.StoreRepository;
import com.mmnaseri.utils.spring.data.dsl.mock.RepositoryMockBuilder;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
public class DefaultStoreServiceTest {
private DefaultStoreService service;
@BeforeMethod
public void setUp() {
final StoreRepository repository = new RepositoryMockBuilder().mock(StoreRepository.class);
service = new DefaultStoreService(repository);
}
@Test
public void testCreateOne() {
final Store store = service.create("My Store");
assertThat(store, is(notNullValue()));
assertThat(store.getName(), is("My Store"));
}
@Test
public void testCreateMultiple() {
final Collection<Store> stores = service.create("Store #1", "Store #2");
assertThat(stores, is(notNullValue()));
assertThat(stores, hasSize(2));
for (Store store : stores) {
assertThat(store.getId(), is(notNullValue()));
assertThat(store.getName(), isIn(Arrays.asList("Store #1", "Store #2")));
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java | spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/StoreService.java | package com.mmnaseri.utils.samples.spring.data.mongo.service;
import com.mmnaseri.utils.samples.spring.data.mongo.model.Store;
import java.util.Collection;
@SuppressWarnings("unused")
public interface StoreService {
Store create(String name);
Collection<Store> create(String... names);
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java | spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/service/impl/DefaultStoreService.java | package com.mmnaseri.utils.samples.spring.data.mongo.service.impl;
import com.mmnaseri.utils.samples.spring.data.mongo.model.Store;
import com.mmnaseri.utils.samples.spring.data.mongo.repository.StoreRepository;
import com.mmnaseri.utils.samples.spring.data.mongo.service.StoreService;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import static java.util.stream.Collectors.toList;
public class DefaultStoreService implements StoreService {
private final StoreRepository repository;
public DefaultStoreService(final StoreRepository repository) {
this.repository = repository;
}
@Override
public Store create(final String name) {
final Store store = new Store().setName(name);
return repository.save(store);
}
@Override
public Collection<Store> create(final String... names) {
final List<Store> stores =
Arrays.stream(names).map(name -> new Store().setName(name)).collect(toList());
return repository.insert(stores);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java | spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/model/Store.java | package com.mmnaseri.utils.samples.spring.data.mongo.model;
import org.bson.types.ObjectId;
@SuppressWarnings("unused")
public class Store {
private ObjectId id;
private String name;
public ObjectId getId() {
return id;
}
public Store setId(final ObjectId id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Store setName(final String name) {
this.name = name;
return this;
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java | spring-data-mock-sample-mongo/src/main/java/com/mmnaseri/utils/samples/spring/data/mongo/repository/StoreRepository.java | package com.mmnaseri.utils.samples.spring.data.mongo.repository;
import com.mmnaseri.utils.samples.spring.data.mongo.model.Store;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface StoreRepository extends MongoRepository<Store, ObjectId> {}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultQueryDescriptorTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.OperatorContext;
import com.mmnaseri.utils.spring.data.domain.Parameter;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableParameter;
import com.mmnaseri.utils.spring.data.query.QueryDescriptor;
import com.mmnaseri.utils.spring.data.sample.models.Address;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultQueryDescriptorTest {
private OperatorContext operatorContext;
@BeforeMethod
public void setUp() {
operatorContext = new DefaultOperatorContext();
}
@Test
public void testGettingPageWhenPageExtractorIsNull() {
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, null, null, null);
assertThat(descriptor.getPage(new ImmutableInvocation(null, new Object[] {})), is(nullValue()));
}
@Test
public void testGettingSortWhenSortExtractorIsNull() {
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, null, null, null);
assertThat(descriptor.getSort(new ImmutableInvocation(null, new Object[] {})), is(nullValue()));
}
@Test
public void testMatchingWhenThereAreNotAnyConditions() {
final List<List<Parameter>> branches = Collections.emptyList();
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
assertThat(descriptor.matches(null, new ImmutableInvocation(null, null)), is(false));
assertThat(descriptor.matches(new Object(), new ImmutableInvocation(null, null)), is(true));
}
@Test
public void testThatEachBranchIsConjunctive() {
final List<List<Parameter>> branches = new ArrayList<>();
final ArrayList<Parameter> branch = new ArrayList<>();
branches.add(branch);
// getByFirstNameAndLastName(:0, :1)
branch.add(
new ImmutableParameter(
"firstName",
Collections.emptySet(),
new int[] {0},
operatorContext.getBySuffix("Equals")));
branch.add(
new ImmutableParameter(
"lastName",
Collections.emptySet(),
new int[] {1},
operatorContext.getBySuffix("IsNot")));
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
final Person person = new Person().setFirstName("X").setLastName("Y");
assertThat(
descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"A", "Y"})),
is(false));
assertThat(
descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"X", "Y"})),
is(false));
assertThat(
descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"A", "B"})),
is(false));
assertThat(
descriptor.matches(person, new ImmutableInvocation(null, new Object[] {"X", "B"})),
is(true));
}
@Test
public void testThatBranchesAreDisjunctive() {
final List<List<Parameter>> branches = new ArrayList<>();
final ArrayList<Parameter> first = new ArrayList<>();
final ArrayList<Parameter> second = new ArrayList<>();
final ArrayList<Parameter> third = new ArrayList<>();
branches.add(first);
branches.add(second);
branches.add(third);
// getByFirstNameAndLastNameOrIdOrAddressCityAndAddressStreet(:0, :1, :2, :3, :4)
first.add(
new ImmutableParameter(
"firstName",
Collections.emptySet(),
new int[] {0},
operatorContext.getBySuffix("Equals")));
first.add(
new ImmutableParameter(
"lastName",
Collections.emptySet(),
new int[] {1},
operatorContext.getBySuffix("Equals")));
second.add(
new ImmutableParameter(
"id", Collections.emptySet(), new int[] {2}, operatorContext.getBySuffix("Equals")));
third.add(
new ImmutableParameter(
"address.city",
Collections.emptySet(),
new int[] {3},
operatorContext.getBySuffix("Equals")));
third.add(
new ImmutableParameter(
"address.street",
Collections.emptySet(),
new int[] {4},
operatorContext.getBySuffix("Equals")));
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
final Person person =
new Person()
.setId("1")
.setFirstName("X")
.setLastName("Y")
.setAddress(new Address().setCity("Shiraz").setStreet("Chaharbagh"));
assertThat(
descriptor.matches(
person, new ImmutableInvocation(null, new Object[] {"X", "Y", "2", "Mashad", "Reza"})),
is(true)); // first branch
assertThat(
descriptor.matches(
person, new ImmutableInvocation(null, new Object[] {"A", "B", "1", "Mashad", "Reza"})),
is(true)); // second branch
assertThat(
descriptor.matches(
person,
new ImmutableInvocation(null, new Object[] {"A", "B", "3", "Shiraz", "Chaharbagh"})),
is(true)); // third branch
assertThat(
descriptor.matches(
person,
new ImmutableInvocation(null, new Object[] {"A", "B", "3", "Tehran", "Tajrish"})),
is(false)); // none
}
@Test
public void testToString() {
final QueryDescriptor noFunctionNotDistinct =
new DefaultQueryDescriptor(false, null, 0, null, null, Collections.emptyList(), null, null);
assertThat(noFunctionNotDistinct.toString(), is("[]"));
final QueryDescriptor functionNotDistinct =
new DefaultQueryDescriptor(
false, "xyz", 0, null, null, Collections.emptyList(), null, null);
assertThat(functionNotDistinct.toString(), is("xyz []"));
final QueryDescriptor functionDistinct =
new DefaultQueryDescriptor(true, "xyz", 0, null, null, Collections.emptyList(), null, null);
assertThat(functionDistinct.toString(), is("xyz distinct []"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/WrappedSortParameterExtractorTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.query.Sort;
import org.testng.annotations.Test;
import java.util.ArrayList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class WrappedSortParameterExtractorTest {
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testPassingNull() {
new WrappedSortParameterExtractor(null);
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testNullInvocation() {
final WrappedSortParameterExtractor extractor =
new WrappedSortParameterExtractor(new ImmutableSort(new ArrayList<>()));
extractor.extract(null);
}
@Test
public void testIdentity() {
final Sort sort = new ImmutableSort(new ArrayList<>());
final WrappedSortParameterExtractor extractor = new WrappedSortParameterExtractor(sort);
assertThat(extractor.extract(new ImmutableInvocation(null, new Object[] {})), is(sort));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DefaultDataFunctionRegistryTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.error.DuplicateFunctionException;
import com.mmnaseri.utils.spring.data.error.FunctionNotFoundException;
import com.mmnaseri.utils.spring.data.query.DataFunction;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultDataFunctionRegistryTest {
@Test
public void testDefaultFunctions() {
final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry();
final Set<String> functions = registry.getFunctions();
final Set<String> expected = new HashSet<>(Arrays.asList("count", "delete"));
assertThat(functions, hasSize(2));
for (String function : functions) {
assertThat(function, isIn(expected));
expected.remove(function);
}
assertThat(expected, is(Matchers.empty()));
}
@Test(expectedExceptions = FunctionNotFoundException.class)
public void testNonExistentFunction() {
final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry();
registry.getFunction("xyz");
}
@Test(expectedExceptions = DuplicateFunctionException.class)
public void testRegisteringDuplicateFunction() {
final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry();
registry.register("count", new DeleteDataFunction());
}
@Test
public void testRegisteringLegitimateFunction() {
final DefaultDataFunctionRegistry registry = new DefaultDataFunctionRegistry();
final String item = "size";
final DataFunction function = new CountDataFunction();
registry.register(item, function);
assertThat(registry.getFunctions(), hasItem(item));
assertThat(registry.getFunction(item), is(function));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DeleteDataFunctionTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.DataFunctionException;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.DataFunction;
import com.mmnaseri.utils.spring.data.query.QueryDescriptor;
import com.mmnaseri.utils.spring.data.sample.mocks.Operation;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataStore;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DeleteDataFunctionTest {
private QueryDescriptor query;
private DeleteDataFunction function;
private SpyingDataStore<String, Person> dataStore;
@BeforeMethod
public void setUp() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, Person.class, null, "id");
final MemoryDataStore<String, Person> delegate = new MemoryDataStore<>(Person.class);
query = new DefaultQueryDescriptor(false, null, 0, null, null, null, null, repositoryMetadata);
function = new DeleteDataFunction();
dataStore = new SpyingDataStore<>(delegate, new AtomicLong());
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = "Data store .*")
public void testPassingNullDataStore() {
final DataFunction<List<?>> function = new DeleteDataFunction();
function.apply(null, query, null, new LinkedList<>());
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = "Query .*")
public void testPassingNullQuery() {
final DataFunction<List<?>> function = new DeleteDataFunction();
function.apply(dataStore, null, null, new LinkedList<>());
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = "Selection .*")
public void testPassingNullSelection() {
function.apply(dataStore, query, null, null);
}
@Test(
expectedExceptions = DataFunctionException.class,
expectedExceptionsMessageRegExp = "Failed to read .*")
public void testWrongIdentifierProperty() {
final DataFunction<List<?>> function = new DeleteDataFunction();
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, Person.class, null, "xyz");
final QueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, null, null, repositoryMetadata);
function.apply(dataStore, descriptor, null, Collections.singletonList(new Person()));
}
@Test(
expectedExceptions = DataFunctionException.class,
expectedExceptionsMessageRegExp =
"Cannot delete an entity without the key property being set: id")
public void testNullIdentifierValue() {
final DataFunction<List<?>> function = new DeleteDataFunction();
function.apply(dataStore, query, null, Collections.singletonList(new Person()));
}
@Test
public void testThatItSendsRequestsToTheUnderlyingDataStore() {
final List<Person> selection = new ArrayList<>();
selection.add(new Person().setId("1"));
selection.add(new Person().setId("2"));
function.apply(dataStore, query, null, selection);
assertThat(dataStore.getRequests(), hasSize(2));
assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(selection.get(0).getId()));
assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(selection.get(1).getId()));
}
@Test
public void testThatItDeletesTheExactSetOfItemsSpecified() {
final List<Person> entities = new ArrayList<>();
entities.add(new Person().setId("1"));
entities.add(new Person().setId("2"));
entities.add(new Person().setId("3"));
entities.add(new Person().setId("4"));
for (Person person : entities) {
dataStore.save(person.getId(), person);
}
dataStore.reset();
final List<Person> selection = entities.subList(1, 3);
function.apply(dataStore, query, null, selection);
assertThat(dataStore.getRequests(), hasSize(2));
assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId()));
assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId()));
assertThat(dataStore.hasKey(entities.get(0).getId()), is(true));
assertThat(dataStore.hasKey(entities.get(1).getId()), is(false));
assertThat(dataStore.hasKey(entities.get(2).getId()), is(false));
assertThat(dataStore.hasKey(entities.get(3).getId()), is(true));
}
@Test
public void testThatItReturnsTheDeletedItems() {
final List<Person> entities = new ArrayList<>();
entities.add(new Person().setId("1"));
entities.add(new Person().setId("2"));
entities.add(new Person().setId("3"));
entities.add(new Person().setId("4"));
for (Person person : entities) {
dataStore.save(person.getId(), person);
}
dataStore.reset();
final List<Person> selection = new ArrayList<>(entities.subList(1, 3));
selection.add(new Person().setId("5"));
final List<Person> deleted = function.apply(dataStore, query, null, selection);
assertThat(dataStore.getRequests(), hasSize(3));
assertThat(dataStore.getRequests().get(0).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(0).getKey(), Matchers.is(entities.get(1).getId()));
assertThat(dataStore.getRequests().get(1).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(1).getKey(), Matchers.is(entities.get(2).getId()));
assertThat(dataStore.getRequests().get(2).getOperation(), is(Operation.DELETE));
assertThat(dataStore.getRequests().get(2).getKey(), Matchers.is(selection.get(2).getId()));
assertThat(deleted, hasSize(2));
final List<String> deletedIds =
new ArrayList<>(Arrays.asList(entities.get(1).getId(), entities.get(2).getId()));
for (Person person : deleted) {
assertThat(person.getId(), isIn(deletedIds));
deletedIds.remove(person.getId());
}
assertThat(deletedIds, is(Collections.<String>emptyList()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageablePageParameterExtractorTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.Page;
import org.springframework.data.domain.PageRequest;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class PageablePageParameterExtractorTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testNullInvocation() {
final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0);
extractor.extract(null);
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingNullValue() {
final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {null}));
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingWrongType() {
final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()}));
}
@Test
public void testPassingPageRequest() {
final PageablePageParameterExtractor extractor = new PageablePageParameterExtractor(0);
final PageRequest pageRequest = PageRequest.of(3, 7);
final Page extracted =
extractor.extract(new ImmutableInvocation(null, new Object[] {pageRequest}));
assertThat(extracted, is(notNullValue()));
assertThat(extracted.getPageNumber(), is(pageRequest.getPageNumber()));
assertThat(extracted.getPageSize(), is(pageRequest.getPageSize()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/CountDataFunctionTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.DataFunction;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.LinkedList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class CountDataFunctionTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testThatNullSelectionResultsInError() {
final DataFunction function = new CountDataFunction();
function.apply(null, null, null, null);
}
@Test
public void testThatItReflectsTheSizeOfTheCollection() {
final DataFunction<Long> function = new CountDataFunction();
final List<Object> selection = new LinkedList<>();
for (int i = 0; i < 10; i++) {
final Long count = function.apply(null, null, null, selection);
assertThat(count, Matchers.is((long) selection.size()));
selection.add(new Object());
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/PageableSortParameterExtractorTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.NullHandling;
import com.mmnaseri.utils.spring.data.query.Sort;
import com.mmnaseri.utils.spring.data.query.SortDirection;
import org.springframework.data.domain.PageRequest;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class PageableSortParameterExtractorTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testNullInvocation() {
final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0);
extractor.extract(null);
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingNullValue() {
final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {null}));
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingWrongType() {
final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()}));
}
@Test
public void testPassingPageableWithNullSort() {
final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0);
final Sort extracted =
extractor.extract(new ImmutableInvocation(null, new Object[] {PageRequest.of(0, 1)}));
assertThat(extracted instanceof ImmutableSort, is(true));
}
@Test
public void testPassingPageableWithNullProperSort() {
final PageableSortParameterExtractor extractor = new PageableSortParameterExtractor(0);
final Sort extracted =
extractor.extract(
new ImmutableInvocation(
null,
new Object[] {
PageRequest.of(
0, 1, org.springframework.data.domain.Sort.Direction.DESC, "a", "b")
}));
assertThat(extracted, is(notNullValue()));
assertThat(extracted.getOrders(), hasSize(2));
assertThat(extracted.getOrders().get(0).getProperty(), is("a"));
assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.DESCENDING));
assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT));
assertThat(extracted.getOrders().get(1).getProperty(), is("b"));
assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.DESCENDING));
assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/query/impl/DirectSortParameterExtractorTest.java | package com.mmnaseri.utils.spring.data.query.impl;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.NullHandling;
import com.mmnaseri.utils.spring.data.query.SortDirection;
import org.springframework.data.domain.Sort;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DirectSortParameterExtractorTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testNullInvocation() {
final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0);
extractor.extract(null);
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingNullSort() {
final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {null}));
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testPassingWrongTypeOfArgument() {
final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0);
extractor.extract(new ImmutableInvocation(null, new Object[] {new Object()}));
}
@Test
public void testPassingSortValue() {
final DirectSortParameterExtractor extractor = new DirectSortParameterExtractor(0);
final com.mmnaseri.utils.spring.data.query.Sort extracted =
extractor.extract(new ImmutableInvocation(null, new Object[] {Sort.by("a", "b")}));
assertThat(extracted, is(notNullValue()));
assertThat(extracted.getOrders(), hasSize(2));
assertThat(extracted.getOrders().get(0).getProperty(), is("a"));
assertThat(extracted.getOrders().get(0).getDirection(), is(SortDirection.ASCENDING));
assertThat(extracted.getOrders().get(0).getNullHandling(), is(NullHandling.DEFAULT));
assertThat(extracted.getOrders().get(1).getProperty(), is("b"));
assertThat(extracted.getOrders().get(1).getDirection(), is(SortDirection.ASCENDING));
assertThat(extracted.getOrders().get(1).getNullHandling(), is(NullHandling.DEFAULT));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/AbstractUtilityClassTest.java | package com.mmnaseri.utils.spring.data.tools;
import org.testng.annotations.Test;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.arrayWithSize;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.testng.Assert.fail;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public abstract class AbstractUtilityClassTest {
protected abstract Class<?> getUtilityClass();
@Test
public void testConstructorIsPrivate() {
final Constructor<?>[] constructors = getUtilityClass().getDeclaredConstructors();
assertThat(constructors, is(arrayWithSize(1)));
final Constructor<?> constructor = constructors[0];
assertThat(Modifier.isPrivate(constructor.getModifiers()), is(true));
}
@Test
public void testConstructorThrowsException() throws Exception {
final Constructor<?>[] constructors = getUtilityClass().getDeclaredConstructors();
final Constructor<?> constructor = constructors[0];
constructor.setAccessible(true);
try {
constructor.newInstance();
} catch (InvocationTargetException e) {
assertThat(e.getCause(), is(notNullValue()));
assertThat(e.getCause(), is(instanceOf(UnsupportedOperationException.class)));
return;
}
fail("Expected utility class constructor to throw an exception");
}
@Test
public void testClassIsFinal() {
assertThat(Modifier.isFinal(getUtilityClass().getModifiers()), is(true));
}
@Test
public void testClassHasNoInstanceMethods() {
for (Method method : getUtilityClass().getDeclaredMethods()) {
assertThat(Modifier.isStatic(method.getModifiers()), is(true));
}
}
@Test
public void testClassHasNoInstanceFields() {
for (Field field : getUtilityClass().getDeclaredFields()) {
assertThat(Modifier.isStatic(field.getModifiers()), is(true));
}
}
@Test
public void testClassHasNoSuperClass() {
assertThat(getUtilityClass().getSuperclass(), is(equalTo((Class) Object.class)));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/StringUtilsTest.java | package com.mmnaseri.utils.spring.data.tools;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class StringUtilsTest extends AbstractUtilityClassTest {
@Override
protected Class<?> getUtilityClass() {
return StringUtils.class;
}
@Test(
expectedExceptions = NullPointerException.class,
expectedExceptionsMessageRegExp = "String value cannot be null")
public void testCapitalizingNullValue() {
StringUtils.capitalize(null);
}
@Test
public void testCapitalizingEmptyString() {
assertThat(StringUtils.capitalize(""), is(""));
}
@Test
public void testCapitalizingUncapitalizedString() {
assertThat(StringUtils.capitalize("hello"), is("Hello"));
}
@Test
public void testCapitalizingCapitalizedString() {
assertThat(StringUtils.capitalize("Hello"), is("Hello"));
}
@Test(
expectedExceptions = NullPointerException.class,
expectedExceptionsMessageRegExp = "String value cannot be null")
public void testUncapitalizingNullValue() {
StringUtils.uncapitalize(null);
}
@Test
public void testUncapitalizingEmptyString() {
assertThat(StringUtils.uncapitalize(""), is(""));
}
@Test
public void testUncapitalizingUncapitalizedString() {
assertThat(StringUtils.uncapitalize("hello"), is("hello"));
}
@Test
public void testUncapitalizingCapitalizedString() {
assertThat(StringUtils.uncapitalize("Hello"), is("hello"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/GetterMethodFilterTest.java | package com.mmnaseri.utils.spring.data.tools;
import com.mmnaseri.utils.spring.data.sample.models.SampleClass;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class GetterMethodFilterTest {
@Test
public void testFailures() throws Exception {
final GetterMethodFilter filter = new GetterMethodFilter();
assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getProperty")), is(false));
assertThat(
filter.matches(SampleClass.class.getDeclaredMethod("getProperty", int.class)), is(false));
assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasProperty")), is(false));
assertThat(
filter.matches(SampleClass.class.getDeclaredMethod("getProperty", String.class)),
is(false));
assertThat(
filter.matches(SampleClass.class.getDeclaredMethod("hasProperty", String.class)),
is(false));
assertThat(filter.matches(SampleClass.class.getDeclaredMethod("hasState")), is(false));
assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getterMethod")), is(false));
}
@Test
public void testProperGetter() throws Exception {
final GetterMethodFilter filter = new GetterMethodFilter();
assertThat(filter.matches(SampleClass.class.getDeclaredMethod("getValue")), is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/PropertyUtilsTest.java | package com.mmnaseri.utils.spring.data.tools;
import com.mmnaseri.utils.spring.data.error.ParserException;
import com.mmnaseri.utils.spring.data.query.PropertyDescriptor;
import com.mmnaseri.utils.spring.data.sample.models.Address;
import com.mmnaseri.utils.spring.data.sample.models.NoAccessorPerson;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.models.State;
import com.mmnaseri.utils.spring.data.sample.models.Zip;
import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithErrorThrowingAccessors;
import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithFinalId;
import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithNoGetters;
import com.mmnaseri.utils.spring.data.sample.usecases.tools.ClassWithPrimitiveField;
import org.hamcrest.Matchers;
import org.springframework.util.ReflectionUtils;
import org.testng.annotations.Test;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Objects;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class PropertyUtilsTest extends AbstractUtilityClassTest {
@Override
protected Class<?> getUtilityClass() {
return PropertyUtils.class;
}
@Test(
expectedExceptions = ParserException.class,
expectedExceptionsMessageRegExp = "Expected pattern '.*?' was not encountered.*")
public void testPropertyPathThatDoesNotStartWithCapitalLetter() {
PropertyUtils.getPropertyDescriptor(Person.class, "address");
}
@Test
public void testFirstLevelPropertyPath() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(Person.class, "Address");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("address"));
assertThat(descriptor.getType(), equalTo((Class) Address.class));
}
@Test
public void testFirstLevelPropertyWithoutExplicitBreaking() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(Person.class, "AddressZip");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("addressZip"));
assertThat(descriptor.getType(), equalTo((Class) Zip.class));
}
@Test
public void testPropertyWithExplicitBreaking() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(Person.class, "Address_Zip");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("address.zip"));
assertThat(descriptor.getType(), equalTo((Class) Zip.class));
}
@Test
public void testMultiLevelPropertyWithoutExplicitBreaking() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(Person.class, "AddressZipPrefix");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("addressZip.prefix"));
assertThat(descriptor.getType(), equalTo((Class) String.class));
}
@Test
public void testMultiLevelPropertyWithExplicitBreaking() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipPrefix");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("address.zip.prefix"));
assertThat(descriptor.getType(), equalTo((Class) String.class));
}
@Test(
expectedExceptions = IllegalStateException.class,
expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Person`")
public void testNonExistingFirstLevelProperty() {
PropertyUtils.getPropertyDescriptor(Person.class, "Xyz");
}
@Test(
expectedExceptions = IllegalStateException.class,
expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`")
public void testNonExistingThirdLevelProperty() {
PropertyUtils.getPropertyDescriptor(Person.class, "Address_ZipXyz");
}
@Test
public void testFirstLevelPropertyWithoutExplicitBreakingUsingFields() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "AddressZip");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("addressZip"));
assertThat(descriptor.getType(), equalTo((Class) Zip.class));
}
@Test
public void testPropertyWithExplicitBreakingUsingFields() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_Zip");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("address.zip"));
assertThat(descriptor.getType(), equalTo((Class) Zip.class));
}
@Test
public void testMultiLevelPropertyWithoutExplicitBreakingUsingFields() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "AddressZipPrefix");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("addressZip.prefix"));
assertThat(descriptor.getType(), equalTo((Class) String.class));
}
@Test
public void testMultiLevelPropertyWithExplicitBreakingUsingFields() {
final PropertyDescriptor descriptor =
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_ZipPrefix");
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getPath(), is("address.zip.prefix"));
assertThat(descriptor.getType(), equalTo((Class) String.class));
}
@Test(
expectedExceptions = IllegalStateException.class,
expectedExceptionsMessageRegExp =
"Could not find property `xyz` on `class .*?\\.NoAccessorPerson`")
public void testNonExistingFirstLevelPropertyUsingFields() {
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Xyz");
}
@Test(
expectedExceptions = IllegalStateException.class,
expectedExceptionsMessageRegExp = "Could not find property `xyz` on `class .*?\\.Zip`")
public void testNonExistingThirdLevelPropertyUsingFields() {
PropertyUtils.getPropertyDescriptor(NoAccessorPerson.class, "Address_ZipXyz");
}
@Test
public void testReadingPropertyValue() {
final Person person = new Person();
person.setAddress(new Address());
person.getAddress().setCity("Tehran");
person.getAddress().setState(new State());
person.getAddress().getState().setName("Teheran");
person.getAddress().getState().setAbbreviation("TEH");
assertThat(PropertyUtils.getPropertyValue(person, "address"), Matchers.is(person.getAddress()));
assertThat(
PropertyUtils.getPropertyValue(person, "address.city"),
Matchers.is(person.getAddress().getCity()));
assertThat(
PropertyUtils.getPropertyValue(person, "address.state.name"),
Matchers.is(person.getAddress().getState().getName()));
assertThat(
PropertyUtils.getPropertyValue(person, "address.state.abbreviation"),
Matchers.is(person.getAddress().getState().getAbbreviation()));
assertThat(PropertyUtils.getPropertyValue(person, "firstName"), is(nullValue()));
}
@Test
public void testPrimitiveTypeConversion() {
assertThat(PropertyUtils.getTypeOf(int.class), is(Matchers.equalTo(Integer.class)));
assertThat(PropertyUtils.getTypeOf(float.class), is(Matchers.equalTo(Float.class)));
assertThat(PropertyUtils.getTypeOf(double.class), is(Matchers.equalTo(Double.class)));
assertThat(PropertyUtils.getTypeOf(byte.class), is(Matchers.equalTo(Byte.class)));
assertThat(PropertyUtils.getTypeOf(short.class), is(Matchers.equalTo(Short.class)));
assertThat(PropertyUtils.getTypeOf(long.class), is(Matchers.equalTo(Long.class)));
assertThat(PropertyUtils.getTypeOf(char.class), is(Matchers.equalTo(Character.class)));
assertThat(PropertyUtils.getTypeOf(boolean.class), is(Matchers.equalTo(Boolean.class)));
}
@Test
public void testNonPrimitiveTypeConversion() {
assertThat(PropertyUtils.getTypeOf(Object.class), is(Matchers.equalTo(Object.class)));
assertThat(PropertyUtils.getTypeOf(String.class), is(Matchers.equalTo(String.class)));
assertThat(PropertyUtils.getTypeOf(BigDecimal.class), is(Matchers.equalTo(BigDecimal.class)));
assertThat(PropertyUtils.getTypeOf(Person.class), is(Matchers.equalTo(Person.class)));
}
@Test
public void testPropertyNameFromGetterMethod() {
assertThat(
PropertyUtils.getPropertyName(
Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddress"))),
is("address"));
assertThat(
PropertyUtils.getPropertyName(
Objects.requireNonNull(ReflectionUtils.findMethod(Person.class, "getAddressZip"))),
is("addressZip"));
}
@Test
public void testReadingPropertyValueThroughField() throws Exception {
final ClassWithNoGetters object = new ClassWithNoGetters();
final Field id =
Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id"));
id.setAccessible(true);
id.set(object, "1234");
assertThat(PropertyUtils.getPropertyValue(object, "id"), is(id.get(object)));
}
@Test(expectedExceptions = IllegalStateException.class)
public void testReadingPropertyValueThroughErrorThrowingGetter() {
final ClassWithErrorThrowingAccessors object = new ClassWithErrorThrowingAccessors();
PropertyUtils.getPropertyValue(object, "id");
}
@Test(expectedExceptions = IllegalStateException.class)
public void testReadingNonExistentProperty() {
final Person person = new Person();
PropertyUtils.getPropertyValue(person, "address.xyz");
}
@Test
public void testReadingWhenMiddlePropertyIsNull() {
assertThat(
PropertyUtils.getPropertyValue(
new Person().setAddress(new Address()), "address.zip.prefix"),
is(nullValue()));
}
@Test
public void testSettingImmediatePropertyValueUsingField() throws Exception {
final ClassWithNoGetters object = new ClassWithNoGetters();
final Field id =
Objects.requireNonNull(ReflectionUtils.findField(ClassWithNoGetters.class, "id"));
id.setAccessible(true);
final String value = "12345";
PropertyUtils.setPropertyValue(object, "id", value);
assertThat(id.get(object), Matchers.is(value));
}
@Test(expectedExceptions = IllegalStateException.class)
public void testSettingImmediatePropertyValueUsingErrorThrowingSetter() {
PropertyUtils.setPropertyValue(new ClassWithErrorThrowingAccessors(), "id", "");
}
@Test
public void testSettingImmediateFinalField() {
PropertyUtils.setPropertyValue(new ClassWithFinalId(), "id", "");
}
@Test(expectedExceptions = IllegalStateException.class)
public void testSettingUnknownProperty() {
PropertyUtils.setPropertyValue(new Person(), "xyz", "");
}
@Test
public void testSettingPropertyThroughSetters() {
final Person person = new Person();
final String value = "123";
final Object changed = PropertyUtils.setPropertyValue(person, "id", value);
assertThat(changed, Matchers.is(person));
assertThat(person.getId(), is(value));
}
@Test
public void testSettingNestedProperty() {
final Person person = new Person().setAddress(new Address().setZip(new Zip()));
final String value = "Capital";
final Object changed = PropertyUtils.setPropertyValue(person, "address.zip.area", value);
assertThat(changed, Matchers.is(person.getAddress().getZip()));
assertThat(person.getAddress().getZip().getArea(), is(value));
}
@Test
public void testSettingPropertyToNullThroughASetter() {
final Person person = new Person().setId("1234");
PropertyUtils.setPropertyValue(person, "id", null);
assertThat(person.getId(), is(nullValue()));
}
@Test(
expectedExceptions = IllegalStateException.class,
expectedExceptionsMessageRegExp = "Failed to set property value through the field .*")
public void testSettingPrimitiveValueToNullThroughSetter() {
PropertyUtils.setPropertyValue(new ClassWithPrimitiveField(), "position", null);
}
@Test(expectedExceptions = IllegalStateException.class)
public void testSettingNestedPropertyWhenParentPropertyIsNull() {
PropertyUtils.setPropertyValue(new Person(), "address.zip", new Zip());
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/tools/CollectionInstanceUtilsTest.java | package com.mmnaseri.utils.spring.data.tools;
import org.testng.annotations.Test;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Deque;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Set;
import java.util.Stack;
import java.util.TreeSet;
import java.util.Vector;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/8/16)
*/
public class CollectionInstanceUtilsTest extends AbstractUtilityClassTest {
@Override
protected Class<?> getUtilityClass() {
return CollectionInstanceUtils.class;
}
@Test
public void testSupportedConcreteTypes() {
final List<? extends Class<?>> collectionTypes =
Arrays.asList(
HashSet.class,
TreeSet.class,
CopyOnWriteArraySet.class,
LinkedHashSet.class,
ArrayList.class,
LinkedList.class,
Vector.class,
Stack.class,
PriorityQueue.class,
PriorityBlockingQueue.class,
ArrayDeque.class,
ConcurrentLinkedQueue.class,
LinkedBlockingQueue.class,
LinkedBlockingDeque.class);
for (Class<?> collectionType : collectionTypes) {
final Collection<?> collection = CollectionInstanceUtils.getCollection(collectionType);
assertThat(collection, is(notNullValue()));
assertThat(collection, is(instanceOf(collectionType)));
}
}
@Test
public void testSupportedAbstractTypes() {
assertThat(CollectionInstanceUtils.getCollection(Set.class), is(instanceOf(Set.class)));
assertThat(CollectionInstanceUtils.getCollection(List.class), is(instanceOf(List.class)));
assertThat(CollectionInstanceUtils.getCollection(Queue.class), is(instanceOf(Queue.class)));
assertThat(CollectionInstanceUtils.getCollection(Deque.class), is(instanceOf(Deque.class)));
assertThat(
CollectionInstanceUtils.getCollection(Collection.class), is(instanceOf(Collection.class)));
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testUnknownType() {
CollectionInstanceUtils.getCollection(Class.class);
}
@Test(expectedExceptions = IllegalArgumentException.class)
public void testNullValue() {
CollectionInstanceUtils.getCollection(null);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultRepositoryFactoryTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultRepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.domain.impl.key.NoOpKeyGenerator;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.ClearableSimpleCrudPersonRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.RepositoryClearerMapping;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.Collection;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultRepositoryFactoryTest {
@Test
public void testRepositoryInstance() {
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration();
final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry();
configuration.setDataStoreRegistry(dataStoreRegistry);
configuration.setDescriptionExtractor(
new MethodQueryDescriptionExtractor(new DefaultOperatorContext()));
configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext());
configuration.setFunctionRegistry(new DefaultDataFunctionRegistry());
configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler());
configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver());
configuration.setResultAdapterContext(new DefaultResultAdapterContext());
configuration.setTypeMappingContext(new DefaultTypeMappingContext());
configuration.setDefaultKeyGenerator(null);
final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration);
assertThat(factory.getConfiguration(), Matchers.is(configuration));
assertThat(dataStoreRegistry.has(Person.class), is(false));
factory.getInstance(
null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class);
assertThat(dataStoreRegistry.has(Person.class), is(true));
final ClearableSimpleCrudPersonRepository repository =
factory.getInstance(
null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class);
final DataStore<Object, Person> dataStore = dataStoreRegistry.getDataStore(Person.class);
dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi"));
dataStore.save("k2", new Person().setId("k2").setLastName("Naseri"));
dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi"));
dataStore.save("k4", new Person().setId("k4").setLastName("Naseri"));
assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray()));
assertThat(
repository.findByLastName("Naseri"),
containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4")));
assertThat(
repository.findByLastName("Sadeghi"),
containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3")));
assertThat(repository.findByLastName("Ghomboli"), is(empty()));
final Collection<Person> all = dataStore.retrieveAll();
assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray()));
dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi"));
dataStore.save("k2", new Person().setId("k2").setLastName("Naseri"));
dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi"));
dataStore.save("k4", new Person().setId("k4").setLastName("Naseri"));
assertThat(dataStore.retrieveAll(), hasSize(4));
repository.clearRepo();
assertThat(dataStore.retrieveAll(), is(empty()));
}
@Test
public void testRepositoryInstanceWithKeyGenerationFallback() {
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration();
final DefaultDataStoreRegistry dataStoreRegistry = new DefaultDataStoreRegistry();
configuration.setDataStoreRegistry(dataStoreRegistry);
configuration.setDescriptionExtractor(
new MethodQueryDescriptionExtractor(new DefaultOperatorContext()));
configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext());
configuration.setFunctionRegistry(new DefaultDataFunctionRegistry());
configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler());
configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver());
configuration.setResultAdapterContext(new DefaultResultAdapterContext());
configuration.setTypeMappingContext(new DefaultTypeMappingContext());
configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>());
final DefaultRepositoryFactory factory = new DefaultRepositoryFactory(configuration);
assertThat(factory.getConfiguration(), Matchers.is(configuration));
assertThat(dataStoreRegistry.has(Person.class), is(false));
factory.getInstance(
null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class);
assertThat(dataStoreRegistry.has(Person.class), is(true));
final ClearableSimpleCrudPersonRepository repository =
factory.getInstance(
null, ClearableSimpleCrudPersonRepository.class, RepositoryClearerMapping.class);
final DataStore<Object, Person> dataStore = dataStoreRegistry.getDataStore(Person.class);
dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi"));
dataStore.save("k2", new Person().setId("k2").setLastName("Naseri"));
dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi"));
dataStore.save("k4", new Person().setId("k4").setLastName("Naseri"));
assertThat(repository.findAll(), containsInAnyOrder(dataStore.retrieveAll().toArray()));
assertThat(
repository.findByLastName("Naseri"),
containsInAnyOrder(dataStore.retrieve("k2"), dataStore.retrieve("k4")));
assertThat(
repository.findByLastName("Sadeghi"),
containsInAnyOrder(dataStore.retrieve("k1"), dataStore.retrieve("k3")));
assertThat(repository.findByLastName("Ghomboli"), is(empty()));
final Collection<Person> all = dataStore.retrieveAll();
assertThat(repository.deleteAll(), containsInAnyOrder(all.toArray()));
dataStore.save("k1", new Person().setId("k1").setLastName("Sadeghi"));
dataStore.save("k2", new Person().setId("k2").setLastName("Naseri"));
dataStore.save("k3", new Person().setId("k3").setLastName("Sadeghi"));
dataStore.save("k4", new Person().setId("k4").setLastName("Naseri"));
assertThat(dataStore.retrieveAll(), hasSize(4));
repository.clearRepo();
assertThat(dataStore.retrieveAll(), is(empty()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultMethodTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultMethodTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.DefaultMethodPersonRepository;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.builder;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
public class DefaultMethodTest {
private DefaultMethodPersonRepository mock;
private DataStore<Object, Person> dataStore;
@BeforeMethod
public void setUp() {
dataStore = new MemoryDataStore<>(Person.class);
mock = builder().registerDataStore(dataStore).mock(DefaultMethodPersonRepository.class);
}
@Test
public void testCallingDefaultMethod() {
dataStore.save("1", new Person().setId("1").setFirstName("Mohammad").setAge(100));
dataStore.save("2", new Person().setId("2").setFirstName("Moses").setAge(110));
dataStore.save("3", new Person().setId("3").setFirstName("Milad").setAge(30));
List<Person> interestingPeople = mock.theInterestingPeople();
assertThat(interestingPeople, is(notNullValue()));
assertThat(interestingPeople, containsInAnyOrder(dataStore.retrieve("1"), dataStore.retrieve("2")));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableRepositoryFactoryConfigurationTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultRepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/12/16, 1:51 PM)
*/
public class ImmutableRepositoryFactoryConfigurationTest {
@Test
public void testCopyConstructor() {
final DefaultRepositoryFactoryConfiguration original =
new DefaultRepositoryFactoryConfiguration();
original.setDescriptionExtractor(
new MethodQueryDescriptionExtractor(new DefaultOperatorContext()));
original.setEventListenerContext(new DefaultDataStoreEventListenerContext());
original.setFunctionRegistry(new DefaultDataFunctionRegistry());
original.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver());
original.setResultAdapterContext(new DefaultResultAdapterContext());
original.setTypeMappingContext(new DefaultTypeMappingContext());
original.setDataStoreRegistry(new DefaultDataStoreRegistry());
original.setOperationInvocationHandler(new NonDataOperationInvocationHandler());
final ImmutableRepositoryFactoryConfiguration copy =
new ImmutableRepositoryFactoryConfiguration(original);
assertThat(copy.getTypeMappingContext(), is(original.getTypeMappingContext()));
assertThat(copy.getResultAdapterContext(), is(original.getResultAdapterContext()));
assertThat(copy.getRepositoryMetadataResolver(), is(original.getRepositoryMetadataResolver()));
assertThat(copy.getOperationInvocationHandler(), is(original.getOperationInvocationHandler()));
assertThat(copy.getFunctionRegistry(), is(original.getFunctionRegistry()));
assertThat(copy.getEventListenerContext(), is(original.getEventListenerContext()));
assertThat(copy.getDescriptionExtractor(), is(original.getDescriptionExtractor()));
assertThat(copy.getDataStoreRegistry(), is(original.getDataStoreRegistry()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/ImmutableInvocationMappingTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.sample.mocks.StringifiableDataStoreOperation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class ImmutableInvocationMappingTest {
@Test
public void testToString() throws Exception {
final String string = "string representation";
final Method method = ReturnTypeSampleRepository.class.getMethod("doSomething");
final ImmutableInvocationMapping<Object, Object> mapping =
new ImmutableInvocationMapping<>(method, new StringifiableDataStoreOperation<>(string));
assertThat(mapping.toString(), is(method.toString() + " -> " + string));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/NonDataOperationInvocationHandlerTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.error.UnknownDataOperationException;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingHandler;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class NonDataOperationInvocationHandlerTest {
@Test
public void testHandlingKnownMethods() throws Throwable {
final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler();
final Object proxy = new Object();
assertThat(
handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[] {}),
Matchers.is(1));
assertThat(
handler.invoke(proxy, Object.class.getMethod("toString"), new Object[] {}),
Matchers.is("mock<[]>"));
assertThat(
handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[] {proxy}),
Matchers.is(false));
assertThat(
handler.invoke(
proxy, Object.class.getMethod("equals", Object.class), new Object[] {new Object()}),
Matchers.is(false));
}
@Test(expectedExceptions = UnknownDataOperationException.class)
public void testUnknownMethod() throws Throwable {
final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler();
handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[] {});
}
@Test
public void testRegisteringMethod() throws Throwable {
final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler();
final SpyingHandler spy = new SpyingHandler();
handler.register(spy);
assertThat(spy.isCalled(), is(false));
handler.invoke(new Object(), Object.class.getMethod("wait"), new Object[0]);
assertThat(spy.isCalled(), is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultResultAdapterContextTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingResultAdapter;
import com.mmnaseri.utils.spring.data.sample.models.Address;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultResultAdapterContextTest {
@Test(expectedExceptions = ResultAdapterFailureException.class)
public void testInvalidConversion() throws Exception {
final DefaultResultAdapterContext context = new DefaultResultAdapterContext();
context.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[] {}),
new Address());
}
@Test
public void testRegisteringOrderedAdapters() throws Exception {
final DefaultResultAdapterContext context = new DefaultResultAdapterContext();
final AtomicLong counter = new AtomicLong();
final Person person = new Person();
final SpyingResultAdapter first = new SpyingResultAdapter(-10000, counter, false, null);
final SpyingResultAdapter second = new SpyingResultAdapter(10000, counter, true, person);
context.register(first);
context.register(second);
final Object result =
context.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPerson"), new Object[] {}),
new Address());
assertThat(first.getCheck(), is(notNullValue()));
assertThat(second.getCheck(), is(notNullValue()));
assertThat(first.getCheck(), is(lessThan(second.getCheck())));
assertThat(first.getRequest(), is(nullValue()));
assertThat(second.getCheck(), is(lessThan(second.getRequest())));
assertThat(result, Matchers.is(person));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DefaultTypeMappingContextTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.repository.DefaultCrudRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultGemfireRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultJpaRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultPagingAndSortingRepository;
import com.mmnaseri.utils.spring.data.repository.DefaultQueryByExampleExecutor;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ErrorThrowingImplementation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.HighPriorityMapping;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ImplementationWithPrivateConstructor;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ImplementationWithoutADefaultConstructor;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.LowerPriorityMapping;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ProperImplementation;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultTypeMappingContextTest {
private Class[] defaultImplementations;
@BeforeMethod
public void setUp() {
defaultImplementations =
new Class[] {
DefaultGemfireRepository.class,
DefaultJpaRepository.class,
DefaultPagingAndSortingRepository.class,
DefaultCrudRepository.class,
DefaultQueryByExampleExecutor.class
};
}
@Test
public void testDefaultMappings() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
assertThat(
context.getImplementations(Object.class),
Matchers.<Class<?>>containsInAnyOrder(defaultImplementations));
}
@Test
public void testRegisteringMappings() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length));
context.register(Double.class, Float.class);
assertThat(
context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1));
assertThat(context.getImplementations(Double.class), hasItem(Float.class));
}
@Test
public void testRegisteringMappingForSupertype() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length));
context.register(Number.class, Float.class);
assertThat(
context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1));
assertThat(context.getImplementations(Double.class), hasItem(Float.class));
}
@Test
public void testRegisteringOrderedMappings() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length));
context.register(Number.class, HighPriorityMapping.class);
context.register(Number.class, LowerPriorityMapping.class);
assertThat(
context.getImplementations(Double.class), hasSize(defaultImplementations.length + 2));
assertThat(context.getImplementations(Double.class), hasItem(LowerPriorityMapping.class));
assertThat(context.getImplementations(Double.class), hasItem(HighPriorityMapping.class));
assertThat(
context.getImplementations(Double.class).indexOf(LowerPriorityMapping.class),
is(lessThan(context.getImplementations(Double.class).indexOf(HighPriorityMapping.class))));
}
@Test
public void testRegisteringWithParent() {
final DefaultTypeMappingContext parent = new DefaultTypeMappingContext();
final DefaultTypeMappingContext context = new DefaultTypeMappingContext(parent);
assertThat(context.getImplementations(Double.class), hasSize(defaultImplementations.length));
parent.register(Number.class, Float.class);
assertThat(
context.getImplementations(Double.class), hasSize(defaultImplementations.length + 1));
assertThat(context.getImplementations(Double.class), hasItem(Float.class));
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testRegisteringAbstractImplementation() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Object.class, AbstractImplementation.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testRegisteringInterfaceImplementation() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Object.class, InterfaceImplementation.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testGettingMappingsWhenConstructorIsPrivate() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Number.class, ImplementationWithPrivateConstructor.class);
context.getMappings(Double.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testGettingMappingsWhenClassIsPrivate() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Number.class, PrivateImplementationClass.class);
context.getMappings(Double.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testGettingMappingsWhenClassHasNoDefaultConstructor() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Number.class, ImplementationWithoutADefaultConstructor.class);
context.getMappings(Double.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class)
public void testGettingMappingsWhenClassThrowsErrors() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Number.class, ErrorThrowingImplementation.class);
context.getMappings(Double.class);
}
@Test
public void testRegisteringAProperImplementation() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
context.register(Number.class, ProperImplementation.class);
final List<TypeMapping<?>> mappings = context.getMappings(Double.class);
assertThat(mappings, hasSize(defaultImplementations.length + 1));
ProperImplementation implementation = null;
for (TypeMapping<?> mapping : mappings) {
assertThat(mapping.getInstance(), is(instanceOf(mapping.getType())));
if (mapping.getType().equals(ProperImplementation.class)) {
implementation = (ProperImplementation) mapping.getInstance();
}
}
assertThat(implementation, is(notNullValue()));
assertThat(implementation.pi(), is(Math.PI));
}
private interface InterfaceImplementation {}
private abstract static class AbstractImplementation {}
private static class PrivateImplementationClass {}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/DataOperationInvocationHandlerTest.java | package com.mmnaseri.utils.spring.data.proxy.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator;
import com.mmnaseri.utils.spring.data.proxy.InvocationMapping;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingOperation;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
public class DataOperationInvocationHandlerTest {
private DataOperationInvocationHandler<String, Person> handler;
private List<InvocationMapping<String, Person>> mappings;
@BeforeMethod
public void setUp() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, Person.class, SimplePersonRepository.class, "id");
final RepositoryConfiguration repositoryConfiguration =
new ImmutableRepositoryConfiguration(
repositoryMetadata, new UUIDKeyGenerator(), Collections.emptyList());
final MemoryDataStore<String, Person> dataStore = new MemoryDataStore<>(Person.class);
final DefaultResultAdapterContext adapterContext = new DefaultResultAdapterContext();
final NonDataOperationInvocationHandler invocationHandler =
new NonDataOperationInvocationHandler();
mappings = new ArrayList<>();
handler =
new DataOperationInvocationHandler<>(
repositoryConfiguration, mappings, dataStore, adapterContext, invocationHandler);
}
/**
* Regression test to reproduce #12
*
* @throws Throwable in case the method can't be found.
*/
@Test
public void testCallingHashCode() throws Throwable {
final Object proxy = new Object();
final Object result =
handler.invoke(proxy, Object.class.getMethod("hashCode"), new Object[] {});
assertThat(result, is(notNullValue()));
assertThat(result, is(1));
}
/** Regression test to reproduce #12 */
@Test
public void testCallingEqualsWhenTheyAreIdentical() throws Throwable {
final Object proxy = new Object();
final Object result =
handler.invoke(proxy, Object.class.getMethod("equals", Object.class), new Object[] {proxy});
assertThat(result, is(notNullValue()));
assertThat(result, is(instanceOf(Boolean.class)));
assertThat(result, is(false));
}
/** Regression test to reproduce #12 */
@Test
public void testCallingEqualsWhenTheyAreNotIdentical() throws Throwable {
final Object proxy = new Object();
final Object result =
handler.invoke(
proxy, Object.class.getMethod("equals", Object.class), new Object[] {new Object()});
assertThat(result, is(notNullValue()));
assertThat(result, is(false));
}
/** Regression test to reproduce #12 */
@Test
public void testCallingToString() throws Throwable {
final Object proxy = new Object();
final Object result =
handler.invoke(proxy, Object.class.getMethod("toString"), new Object[] {});
assertThat(result, is(notNullValue()));
assertThat(result, is("mock<[]>"));
}
@Test
public void testMissingMethodTwice() throws Throwable {
assertThat(
handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[] {}),
is(notNullValue()));
assertThat(
handler.invoke(new Object(), Object.class.getMethod("toString"), new Object[] {}),
is(notNullValue()));
}
@Test
public void testInvokingBoundMapping() throws Throwable {
final Object originalValue = new Object();
final SpyingOperation spy = new SpyingOperation(originalValue);
mappings.add(
new ImmutableInvocationMapping<>(
ReturnTypeSampleRepository.class.getMethod("findOther"), spy));
final Object[] args = {1, 2, 3};
final Object result =
handler.invoke(new Object(), ReturnTypeSampleRepository.class.getMethod("findOther"), args);
assertThat(spy.getInvocation(), is(notNullValue()));
assertThat(
spy.getInvocation().getMethod(),
is(ReturnTypeSampleRepository.class.getMethod("findOther")));
assertThat(spy.getInvocation().getArguments(), is(args));
assertThat(result, is(originalValue));
}
@Test
public void testInvokingBoundMappingTwice() throws Throwable {
final Object originalValue = new Object();
final SpyingOperation spy = new SpyingOperation(originalValue);
final SpyingOperation otherSpy = new SpyingOperation(originalValue);
mappings.add(new ImmutableInvocationMapping<>(Object.class.getMethod("hashCode"), otherSpy));
mappings.add(
new ImmutableInvocationMapping<>(
ReturnTypeSampleRepository.class.getMethod("findOther"), spy));
assertThat(
handler.invoke(
new Object(),
ReturnTypeSampleRepository.class.getMethod("findOther"),
new Object[] {1, 2, 3}),
is(originalValue));
assertThat(
handler.invoke(
new Object(),
ReturnTypeSampleRepository.class.getMethod("findOther"),
new Object[] {4, 5, 6}),
is(originalValue));
assertThat(otherSpy.getInvocation(), is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/AbstractResultConverterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.converters.NoOpResultConverter;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public class AbstractResultConverterTest {
@Test
public void testConversionWhenInputIsNull() {
final Object converted = new NoOpResultConverter().convert(null, null);
assertThat(converted, is(nullValue()));
}
@Test
public void testConversionWhenTargetReturnsVoid() throws Exception {
final Object converted =
new NoOpResultConverter()
.convert(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("doSomething"), null),
new Object());
assertThat(converted, is(nullValue()));
}
@Test
public void testWhenTypeMatchesTheReturnType() throws Exception {
final Person original = new Person();
final Object converted =
new NoOpResultConverter()
.convert(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPerson"), null),
original);
assertThat(converted, is(notNullValue()));
assertThat(converted, is(instanceOf(Person.class)));
assertThat(converted, is(original));
}
@Test
public void testThatPassesToSubClassOtherwise() throws Exception {
final Object original = new Object();
final NoOpResultConverter converter = new NoOpResultConverter();
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPerson"), null),
original);
assertThat(converted, is(notNullValue()));
assertThat(converted, is(original));
assertThat(converter.getOriginal(), is(original));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/IteratorToIterableConverterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public class IteratorToIterableConverterTest {
@Test
public void testConvertingIteratorToIterable() throws Exception {
final IteratorToIterableConverter converter = new IteratorToIterableConverter();
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
Arrays.asList(1, 2, 3, 4).iterator());
assertThat(converted, is(notNullValue()));
assertThat(converted, is(instanceOf(Iterable.class)));
final Iterable iterable = (Iterable) converted;
final Iterator iterator = iterable.iterator();
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), equalTo(1));
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), equalTo(2));
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), equalTo(3));
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), equalTo(4));
assertThat(iterator.hasNext(), is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/SingleValueToIterableConverterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public class SingleValueToIterableConverterTest {
@Test
public void testConvertingSingleValueToIterable() throws Exception {
final SingleValueToIterableConverter converter = new SingleValueToIterableConverter();
final Object original = new Object();
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
original);
assertThat(converted, is(notNullValue()));
assertThat(converted, is(instanceOf(Iterable.class)));
final Iterable<?> iterable = (Iterable<?>) converted;
final Iterator<?> iterator = iterable.iterator();
assertThat(iterator.hasNext(), is(true));
assertThat(iterator.next(), is(original));
assertThat(iterator.hasNext(), is(false));
}
@Test
public void testConvertingIterableToIterable() throws Exception {
final SingleValueToIterableConverter converter = new SingleValueToIterableConverter();
final Object original = Arrays.asList(1, 2, 3);
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
original);
assertThat(converted, is(original));
}
@Test
public void testConvertingIteratorToIterable() throws Exception {
final SingleValueToIterableConverter converter = new SingleValueToIterableConverter();
final Object original = Arrays.asList(1, 2, 3).iterator();
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
original);
assertThat(converted, is(original));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/converters/FutureToIterableConverterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.converters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultConversionFailureException;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ErrorThrowingCallable;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Iterator;
import java.util.concurrent.FutureTask;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/6/15)
*/
public class FutureToIterableConverterTest {
@Test
public void testConvertingFutureValueToIterable() throws Exception {
final FutureToIterableConverter converter = new FutureToIterableConverter();
final Object original = new Object();
final FutureTask<Object> task = new FutureTask<>(() -> original);
task.run();
final Object converted =
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
task);
assertThat(converted, is(notNullValue()));
assertThat(converted, is(instanceOf(Iterable.class)));
//noinspection unchecked
final Iterable<Object> iterable = (Iterable<Object>) converted;
final Iterator<Object> iterator = iterable.iterator();
assertThat(iterator.hasNext(), is(true));
final Object value = iterator.next();
assertThat(value, is(notNullValue()));
assertThat(value, is(original));
assertThat(iterator.hasNext(), is(false));
}
@Test(expectedExceptions = ResultConversionFailureException.class)
public void testConvertingFutureError() throws Exception {
final FutureToIterableConverter converter = new FutureToIterableConverter();
final FutureTask<Object> task = new FutureTask<>(new ErrorThrowingCallable());
task.run();
converter.convert(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findLong"), null),
task);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullSimpleResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullSimpleResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}),
null),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
null),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
null),
is(false));
}
@Test
public void testAdaptingNull() throws Exception {
final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter();
final Object value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null);
assertThat(value, is(nullValue()));
}
@Test(expectedExceptions = ResultAdapterFailureException.class)
public void testAdaptingPrimitiveToNull() throws Exception {
final NullSimpleResultAdapter adapter = new NullSimpleResultAdapter();
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPrimitive"), new Object[] {}),
null);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToSliceResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullToSliceResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final ResultAdapter<Slice> adapter = new NullToSliceResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}),
null),
is(true));
}
@Test
public void testAdaptingToASlice() throws Exception {
final ResultAdapter<Slice> adapter = new NullToSliceResultAdapter();
final Slice<?> value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.getNumber(), is(0));
assertThat(value.getNumberOfElements(), is(0));
assertThat(value.getSize(), is(0));
assertThat(value.getSort(), is(Sort.unsorted()));
assertThat(value.getContent(), hasSize(0));
}
@Test
public void testAdaptingToAPage() throws Exception {
final ResultAdapter<Slice> adapter = new NullToSliceResultAdapter();
final Slice<?> value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.getNumber(), is(0));
assertThat(value.getNumberOfElements(), is(0));
assertThat(value.getSize(), is(0));
assertThat(value.getSort(), is(Sort.unsorted()));
assertThat(value.getContent(), hasSize(0));
}
@Test
public void testAdaptingToAGeoPage() throws Exception {
final ResultAdapter<Slice> adapter = new NullToSliceResultAdapter();
final Slice<?> value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.getNumber(), is(0));
assertThat(value.getNumberOfElements(), is(0));
assertThat(value.getSize(), is(0));
assertThat(value.getSort(), is(Sort.unsorted()));
assertThat(value.getContent(), hasSize(0));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToFutureResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.concurrent.Future;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullToFutureResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final ResultAdapter<Future> adapter = new NullToFutureResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(false));
}
@Test
public void testAdaptingFuture() throws Exception {
final ResultAdapter<Future> adapter = new NullToFutureResultAdapter();
final Future value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.get(), is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/IteratorIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class IteratorIterableResultAdapterTest {
@Test
public void testAdapting() throws Exception {
final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter();
final Iterator<?> value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), null),
Arrays.asList(1, 2, 3, 4));
assertThat(value, is(notNullValue()));
int count = 0;
while (value.hasNext()) {
final Object item = value.next();
assertThat(item, isIn(new Object[] {1, 2, 3, 4}));
count++;
}
assertThat(count, is(4));
}
@Test
public void testAccepting() throws Exception {
final IteratorIterableResultAdapter adapter = new IteratorIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
new ArrayList<>()),
is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/PageIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.springframework.data.domain.Sort;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class PageIterableResultAdapterTest {
@Test
public void testAdapting() throws Exception {
final PageIterableResultAdapter adapter = new PageIterableResultAdapter();
final org.springframework.data.domain.Page<?> value =
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findPage"), null),
Arrays.asList(1, 2, 3, 4));
assertThat(value, is(notNullValue()));
assertThat(value.getTotalElements(), is(4L));
assertThat(value.getTotalPages(), is(1));
assertThat(value.getNumber(), is(0));
assertThat(value.getNumberOfElements(), is(4));
assertThat(value.getSize(), is(4));
assertThat(value.getSort(), is(Sort.unsorted()));
assertThat(value.getContent(), hasSize(4));
assertThat(value.getContent(), containsInAnyOrder(1, 2, 3, 4));
}
@Test
public void testAccepting() throws Exception {
final PageIterableResultAdapter adapter = new PageIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findPage"), new Object[] {}),
new ArrayList<>()),
is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/FutureIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.concurrent.Future;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class FutureIterableResultAdapterTest {
@Test
public void testAdapting() throws Exception {
final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter();
final Future<?> value =
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findFuture"), null),
Arrays.asList(1, 2, 3, 4));
assertThat(value, is(notNullValue()));
assertThat(value.get(), is(instanceOf((Class) Collection.class)));
final Collection<?> collection = (Collection<?>) value.get();
assertThat(collection, hasSize(4));
assertThat(collection, containsInAnyOrder(1, 2, 3, 4));
}
@Test
public void testAccepting() throws Exception {
final FutureIterableResultAdapter adapter = new FutureIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
new ArrayList<>()),
is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/VoidResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class VoidResultAdapterTest {
@Test
public void testAccepting() throws Exception {
final VoidResultAdapter adapter = new VoidResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[] {}),
null),
is(true));
}
@Test
public void testAdapting() throws Exception {
final VoidResultAdapter adapter = new VoidResultAdapter();
final Object adapted =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("doSomething"), new Object[] {}),
new Object());
assertThat(adapted, is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/ListenableFutureIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.hamcrest.Matchers;
import org.springframework.util.concurrent.ListenableFuture;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class ListenableFutureIterableResultAdapterTest {
@Test
public void testAccepting() throws Exception {
final ListenableFutureIterableResultAdapter adapter =
new ListenableFutureIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findListenableFuture"),
new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findListenableFuture"),
new Object[] {}),
new ArrayList<>()),
is(true));
}
@Test
public void testAdapting() throws Exception {
final ListenableFutureIterableResultAdapter adapter =
new ListenableFutureIterableResultAdapter();
final List<Integer> originalValue = Arrays.asList(1, 2, 3);
final ListenableFuture adapted =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findListenableFuture"),
new Object[] {}),
originalValue);
assertThat(adapted, is(notNullValue()));
final Object result = adapted.get();
assertThat(result, is(notNullValue()));
assertThat(result, Matchers.is(originalValue));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SimpleIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class SimpleIterableResultAdapterTest {
@Test
public void testAdaptingEmptyCollection() throws Exception {
final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter();
final Object value =
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null),
Collections.emptyList());
assertThat(value, is(nullValue()));
}
@Test
public void testAdaptingSingletonList() throws Exception {
final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter();
final Object value =
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null),
Collections.singletonList(1));
assertThat(value, is(notNullValue()));
assertThat(value, is(1));
}
@Test(
expectedExceptions = ResultAdapterFailureException.class,
expectedExceptionsMessageRegExp = ".*?; Expected only one item but found many")
public void testAdaptingMultiItemList() throws Exception {
final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter();
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null),
Arrays.asList(1, 2, 3));
}
@Test(
expectedExceptions = ResultAdapterFailureException.class,
expectedExceptionsMessageRegExp =
"Could not adapt value: <hello> to type <class java.lang.Integer>; "
+ "Expected value to be of the indicated type")
public void testAdaptingIncompatibleValue() throws Exception {
final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter();
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findInteger"), null),
Collections.singletonList("hello"));
}
@Test
public void testAccepting() throws Exception {
final SimpleIterableResultAdapter adapter = new SimpleIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFuture"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new ArrayList<>()),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}),
new ArrayList<>()),
is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/GeoPageIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.springframework.data.domain.Sort;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoPage;
import org.springframework.data.geo.GeoResult;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class GeoPageIterableResultAdapterTest {
@Test
public void testAdapting() throws Exception {
final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter();
final GeoResult[] geoResults = {
new GeoResult<>(1, new Distance(0)), new GeoResult<>(2, new Distance(1)),
new GeoResult<>(3, new Distance(1)), new GeoResult<>(4, new Distance(2))
};
final GeoPage<?> value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findGeoPage"), null),
Arrays.asList(geoResults));
assertThat(value, is(notNullValue()));
assertThat(value.getAverageDistance(), is(new Distance(1)));
assertThat(value.getNumber(), is(0));
assertThat(value.getNumberOfElements(), is(4));
assertThat(value.getSize(), is(4));
assertThat(value.getTotalElements(), is(4L));
assertThat(value.getTotalPages(), is(1));
assertThat(value.getSort(), is(Sort.unsorted()));
assertThat(value.getContent(), hasSize(4));
assertThat(value.getContent(), containsInAnyOrder(geoResults));
}
@Test
public void testAccepting() throws Exception {
final GeoPageIterableResultAdapter adapter = new GeoPageIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findGeoPage"), new Object[] {}),
new ArrayList<>()),
is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullToIterableResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final ResultAdapter<Iterable> adapter = new NullToIterableResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(false));
}
@Test
public void testAdaptingToIterable() throws Exception {
final ResultAdapter<Iterable> adapter = new NullToIterableResultAdapter();
final Iterable value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterable"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.iterator(), is(notNullValue()));
final Iterator iterator = value.iterator();
assertThat(iterator.hasNext(), is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToListenableFutureResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.springframework.util.concurrent.ListenableFuture;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class NullToListenableFutureResultAdapterTest {
@Test
public void testAccepting() throws Exception {
final ResultAdapter<ListenableFuture> adapter = new NullToListenableFutureResultAdapter();
assertThat(adapter.accepts(null, new Object()), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findListenableFuture"),
new Object[] {}),
null),
is(true));
}
@Test
public void testAdaptingTheResult() throws Exception {
final ResultAdapter<ListenableFuture> adapter = new NullToListenableFutureResultAdapter();
final ListenableFuture adapted =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findListenableFuture"),
new Object[] {}),
null);
assertThat(adapted, is(notNullValue()));
assertThat(adapted.get(), is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/SliceIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.springframework.data.domain.Slice;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class SliceIterableResultAdapterTest {
@Test
public void testAccepting() throws Exception {
final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}),
new ArrayList<>()),
is(true));
}
@Test
public void testAdapting() throws Exception {
final SliceIterableResultAdapter adapter = new SliceIterableResultAdapter();
final List<Object> originalValue = Arrays.asList(1, 2, 3, 4);
final Slice slice =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSlice"), new Object[] {}),
originalValue);
assertThat(slice, is(notNullValue()));
assertThat(slice.getNumberOfElements(), is(originalValue.size()));
final List content = slice.getContent();
for (Object item : content) {
assertThat(item, isIn(originalValue));
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/EmptyIteratorTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class EmptyIteratorTest {
@Test
public void testHasNext() {
assertThat(EmptyIterator.INSTANCE.hasNext(), is(false));
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testNext() {
EmptyIterator.INSTANCE.next();
}
@Test(expectedExceptions = IndexOutOfBoundsException.class)
public void testRemove() {
EmptyIterator.INSTANCE.remove();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/CollectionIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class CollectionIterableResultAdapterTest {
@Test
public void testAdapting() throws Exception {
final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter();
final Collection<?> value =
adapter.adapt(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null),
Arrays.asList(1, 2, 3, 4, 5, 4, 3, 2, 1));
assertThat(value, is(notNullValue()));
assertThat(value, hasSize(5));
assertThat(value, is(instanceOf(Set.class)));
assertThat(value, containsInAnyOrder(1, 2, 3, 4, 5));
}
@Test(expectedExceptions = ResultAdapterFailureException.class)
public void testAdaptingCustomCollectionImplementation() throws Exception {
final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter();
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null),
null);
}
@Test
public void testAccepts() throws Exception {
final CollectionIterableResultAdapter adapter = new CollectionIterableResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null),
null),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findCustomCollection"), null),
new ArrayList<>()),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findSet"), null),
new ArrayList<>()),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(ReturnTypeSampleRepository.class.getMethod("findOther"), null),
new ArrayList<>()),
is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToCollectionResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullToCollectionResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final ResultAdapter<Collection> adapter = new NullToCollectionResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[] {}),
null),
is(true));
}
@Test
public void testAdaptingList() throws Exception {
final ResultAdapter<Collection> adapter = new NullToCollectionResultAdapter();
final Collection<?> collection =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findList"), new Object[] {}),
null);
assertThat(collection, is(notNullValue()));
assertThat(collection, hasSize(0));
assertThat(collection, is(instanceOf(List.class)));
}
@Test
public void testAdaptingSet() throws Exception {
final ResultAdapter<Collection> adapter = new NullToCollectionResultAdapter();
final Collection<?> collection =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findSet"), new Object[] {}),
null);
assertThat(collection, is(notNullValue()));
assertThat(collection, hasSize(0));
assertThat(collection, is(instanceOf(Set.class)));
}
@Test
public void testAdaptingQueue() throws Exception {
final ResultAdapter<Collection> adapter = new NullToCollectionResultAdapter();
final Collection<?> collection =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findQueue"), new Object[] {}),
null);
assertThat(collection, is(notNullValue()));
assertThat(collection, hasSize(0));
assertThat(collection, is(instanceOf(Queue.class)));
}
@Test
public void testAdaptingConcreteCollection() throws Exception {
final ResultAdapter<Collection> adapter = new NullToCollectionResultAdapter();
final Collection<?> collection =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findLinkedList"), new Object[] {}),
null);
assertThat(collection, is(notNullValue()));
assertThat(collection, hasSize(0));
assertThat(collection, is(instanceOf(LinkedList.class)));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NullToIteratorResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.proxy.ResultAdapter;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.testng.annotations.Test;
import java.util.Iterator;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/5/15)
*/
public class NullToIteratorResultAdapterTest {
@Test
public void testAcceptance() throws Exception {
final ResultAdapter<Iterator> adapter = new NullToIteratorResultAdapter();
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
null),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
null),
is(false));
}
@Test
public void testAdaptingToIterable() throws Exception {
final ResultAdapter<Iterator> adapter = new NullToIteratorResultAdapter();
final Iterator value =
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findIterator"), new Object[] {}),
null);
assertThat(value, is(notNullValue()));
assertThat(value.hasNext(), is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/adapters/NumberIterableResultAdapterTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.adapters;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableInvocation;
import com.mmnaseri.utils.spring.data.error.ResultAdapterFailureException;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.ReturnTypeSampleRepository;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class NumberIterableResultAdapterTest {
@Test
public void testAccepting() throws Exception {
final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter();
assertThat(adapter.accepts(null, null), is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findOther"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}),
new Object()),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}),
Arrays.asList("", 1)),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}),
Arrays.asList(1, 2)),
is(false));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}),
Collections.singletonList(1)),
is(true));
assertThat(
adapter.accepts(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInteger"), new Object[] {}),
Collections.singletonList(1)),
is(true));
}
@Test
public void testAdapting() throws Exception {
final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter();
Long value = 100L;
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findInt"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value.intValue()));
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findLong"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value));
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findShort"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value.shortValue()));
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findDouble"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value.doubleValue()));
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findFloat"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value.floatValue()));
assertThat(
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findByte"), new Object[] {}),
Collections.singleton(value)),
Matchers.is(value.byteValue()));
}
@Test(expectedExceptions = ResultAdapterFailureException.class)
public void testAdaptingUnsupportedNumberType() throws Exception {
final NumberIterableResultAdapter adapter = new NumberIterableResultAdapter();
adapter.adapt(
new ImmutableInvocation(
ReturnTypeSampleRepository.class.getMethod("findBigDecimal"), new Object[] {}),
Collections.singletonList(1));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/SignatureDataOperationResolverTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.proxy.impl.ImmutableTypeMapping;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.ChildClass;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.ProxiedClass;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperClass;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperInterface;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SuperInterfaceImpl;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class SignatureDataOperationResolverTest {
private SignatureDataOperationResolver resolver;
@BeforeMethod
public void setUp() {
final List<TypeMapping<?>> mappings = new ArrayList<>();
mappings.add(new ImmutableTypeMapping<>(SuperInterface.class, new SuperInterfaceImpl()));
mappings.add(new ImmutableTypeMapping<>(ChildClass.class, new ChildClass()));
resolver = new SignatureDataOperationResolver(mappings);
}
@Test
public void testLookingForExactMatchViaInterface() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Double.class));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class)));
final MethodInvocationDataStoreOperation invocationOperation =
(MethodInvocationDataStoreOperation) operation;
assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class)));
assertThat(
invocationOperation.getMethod(),
is(SuperInterface.class.getMethod("saySomething", CharSequence.class, Double.class)));
}
@Test
public void testLookingForExactMatchViaClass() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Integer.class));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class)));
final MethodInvocationDataStoreOperation invocationOperation =
(MethodInvocationDataStoreOperation) operation;
assertThat(invocationOperation.getInstance(), is(instanceOf(ChildClass.class)));
assertThat(
invocationOperation.getMethod(),
is(ChildClass.class.getMethod("saySomething", String.class, Integer.class)));
}
@Test
public void testLookingForMatchViaSuperClassSuperSignature() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, float.class));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class)));
final MethodInvocationDataStoreOperation invocationOperation =
(MethodInvocationDataStoreOperation) operation;
assertThat(invocationOperation.getInstance(), is(instanceOf(SuperClass.class)));
assertThat(
invocationOperation.getMethod(),
is(SuperClass.class.getMethod("saySomething", CharSequence.class, Number.class)));
}
@Test
public void testLookingForMaskedMethod() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(ProxiedClass.class.getMethod("doSomething"));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class)));
final MethodInvocationDataStoreOperation invocationOperation =
(MethodInvocationDataStoreOperation) operation;
assertThat(invocationOperation.getInstance(), is(instanceOf(SuperInterface.class)));
assertThat(invocationOperation.getMethod(), is(SuperInterface.class.getMethod("doSomething")));
}
@Test
public void testLookingForMethodThatDoesNotMatch() throws Exception {
final DataStoreOperation<?, ?, ?> resolved =
resolver.resolve(ProxiedClass.class.getMethod("saySomething", String.class, Boolean.class));
assertThat(resolved, is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/DefaultDataOperationResolverTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.DescribedDataStoreOperation;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.MethodInvocationDataStoreOperation;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.error.DataOperationDefinitionException;
import com.mmnaseri.utils.spring.data.error.UnknownDataOperationException;
import com.mmnaseri.utils.spring.data.proxy.TypeMapping;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.impl.ImmutableTypeMapping;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.MappedType;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SampleMappedRepository;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultDataOperationResolverTest {
private DefaultDataOperationResolver resolver;
@BeforeMethod
public void setUp() {
final ArrayList<TypeMapping<?>> mappings = new ArrayList<>();
mappings.add(new ImmutableTypeMapping<>(MappedType.class, new MappedType()));
final MethodQueryDescriptionExtractor descriptionExtractor =
new MethodQueryDescriptionExtractor(new DefaultOperatorContext());
final ImmutableRepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, Person.class, SampleMappedRepository.class, "id");
final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry();
resolver =
new DefaultDataOperationResolver(
mappings,
descriptionExtractor,
repositoryMetadata,
functionRegistry,
new DefaultRepositoryFactoryConfiguration());
}
@Test
public void testLookingForMethodThatHasMapping() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(SampleMappedRepository.class.getMethod("mappedSignature", String.class));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(MethodInvocationDataStoreOperation.class)));
final MethodInvocationDataStoreOperation invocation =
(MethodInvocationDataStoreOperation) operation;
assertThat(invocation.getInstance(), is(instanceOf(MappedType.class)));
assertThat(
invocation.getMethod(),
is(MappedType.class.getMethod("mappedSignature", CharSequence.class)));
}
@Test
public void testLookingForQueryMethod() throws Exception {
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(SampleMappedRepository.class.getMethod("findByFirstName", String.class));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class)));
}
@Test(expectedExceptions = UnknownDataOperationException.class)
public void testLookingForUnmappedMethod() throws Exception {
resolver.resolve(SampleMappedRepository.class.getMethod("nativeMethod"));
}
@Test(expectedExceptions = DataOperationDefinitionException.class)
public void testLookingForMalformedMethod() throws Exception {
resolver.resolve(SampleMappedRepository.class.getMethod("normalMethodBy"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/proxy/impl/resolvers/QueryMethodDataOperationResolverTest.java | package com.mmnaseri.utils.spring.data.proxy.impl.resolvers;
import com.mmnaseri.utils.spring.data.domain.impl.DescribedDataStoreOperation;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.NoOpMethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.resolvers.SampleMappedRepository;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class QueryMethodDataOperationResolverTest {
@Test
public void testThatItCallsAQueryExtractor() throws Exception {
final NoOpMethodQueryDescriptionExtractor extractor = new NoOpMethodQueryDescriptionExtractor();
final QueryMethodDataOperationResolver resolver =
new QueryMethodDataOperationResolver(extractor, null, null, null);
assertThat(extractor.isCalled(), is(false));
final DataStoreOperation<?, ?, ?> operation =
resolver.resolve(SampleMappedRepository.class.getMethod("normalMethodBy"));
assertThat(operation, is(notNullValue()));
assertThat(operation, is(instanceOf(DescribedDataStoreOperation.class)));
assertThat(extractor.isCalled(), is(true));
}
@Test
public void testMethodThatIsAnnotatedWithVendorQuery() throws Exception {
final QueryMethodDataOperationResolver resolver =
new QueryMethodDataOperationResolver(
new NoOpMethodQueryDescriptionExtractor(), null, null, null);
final DataStoreOperation<?, ?, ?> method =
resolver.resolve(SampleMappedRepository.class.getMethod("nativeMethod"));
assertThat(method, is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/MemoryDataStoreTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.DataStoreException;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class MemoryDataStoreTest {
private MemoryDataStore<String, Person> dataStore;
@BeforeMethod
public void setUp() {
dataStore = new MemoryDataStore<>(Person.class);
}
@Test
public void testEntityType() {
assertThat(dataStore.getEntityType(), is(equalTo(Person.class)));
}
@Test
public void testSaveAndRetrieve() {
assertThat(dataStore.retrieveAll(), is(Matchers.empty()));
final Person person = new Person();
dataStore.save("key", person);
assertThat(dataStore.retrieveAll(), hasSize(1));
}
@Test
public void testRetrievalByKey() {
final Person person = new Person();
final String key = "key";
assertThat(dataStore.retrieve(key), is(nullValue()));
assertThat(dataStore.retrieve(key + "x"), is(nullValue()));
dataStore.save(key, person);
assertThat(dataStore.retrieve(key), is(person));
assertThat(dataStore.retrieve(key + "x"), is(nullValue()));
}
@Test
public void testExistence() {
final Person person = new Person();
final String key = "key";
assertThat(dataStore.hasKey(key), is(false));
assertThat(dataStore.hasKey(key + "x"), is(false));
dataStore.save(key, person);
assertThat(dataStore.hasKey(key), is(true));
assertThat(dataStore.hasKey(key + "x"), is(false));
}
@Test
public void testSaveAndDelete() {
final Person person1 = new Person();
final Person person2 = new Person();
final String key1 = "key1";
final String key2 = "key2";
assertThat(dataStore.retrieveAll(), is(Matchers.empty()));
dataStore.save(key1, person1);
assertThat(dataStore.hasKey(key1), is(true));
dataStore.save(key2, person2);
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(2));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2));
dataStore.delete(key1 + "x");
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(2));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person1, person2));
dataStore.delete(key1);
assertThat(dataStore.hasKey(key1), is(false));
assertThat(dataStore.hasKey(key2), is(true));
assertThat(dataStore.retrieveAll(), hasSize(1));
assertThat(dataStore.retrieveAll(), containsInAnyOrder(person2));
dataStore.delete(key2);
assertThat(dataStore.hasKey(key1), is(false));
assertThat(dataStore.hasKey(key2), is(false));
assertThat(dataStore.retrieveAll(), is(Matchers.empty()));
}
@Test
public void testKeys() {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
assertThat(dataStore.keys(), containsInAnyOrder("1", "2", "3"));
}
@Test(expectedExceptions = DataStoreException.class)
public void testSavingWithNullKey() {
dataStore.save(null, new Person());
}
@Test(expectedExceptions = DataStoreException.class)
public void testSavingWithNullEntity() {
dataStore.save("1", null);
}
@Test(expectedExceptions = DataStoreException.class)
public void testDeletingWithNullKey() {
dataStore.delete(null);
}
@Test(expectedExceptions = DataStoreException.class)
public void testRetrievingWithNullKey() {
dataStore.retrieve(null);
}
@Test
public void testTruncating() {
dataStore.save("1", new Person());
dataStore.save("2", new Person());
dataStore.save("3", new Person());
assertThat(dataStore.retrieveAll(), hasSize(3));
dataStore.truncate();
assertThat(dataStore.retrieveAll(), is(Matchers.empty()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/PropertyVisitorTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithAnnotationOnIdFieldAndGetter;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.LastModifiedBy;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class PropertyVisitorTest {
@Test
public void testLookingForFieldWithAnnotation() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(Id.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field"));
assertThat(visitor.getProperty(), is("field"));
}
@Test
public void testLookingForFieldWithWrongAnnotation() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field"));
assertThat(visitor.getProperty(), is(nullValue()));
}
@Test
public void testLookingForMethodWithAnnotation() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(Id.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty"));
assertThat(visitor.getProperty(), is("property"));
}
@Test
public void testLookingForMethodWithWrongAnnotation() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(LastModifiedBy.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty"));
assertThat(visitor.getProperty(), is(nullValue()));
}
@Test
public void testLookingFieldFirst() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(Id.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field"));
assertThat(visitor.getProperty(), is("field"));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty"));
assertThat(visitor.getProperty(), is("field"));
}
@Test
public void testLookingMethodFirst() throws Exception {
final PropertyVisitor visitor = new PropertyVisitor(Id.class);
assertThat(visitor.getProperty(), is(nullValue()));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredMethod("getProperty"));
assertThat(visitor.getProperty(), is("property"));
visitor.doWith(EntityWithAnnotationOnIdFieldAndGetter.class.getDeclaredField("field"));
assertThat(visitor.getProperty(), is("property"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreEventListenerContextTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.sample.mocks.AfterInsertEventListener;
import com.mmnaseri.utils.spring.data.sample.mocks.AllCatchingEventListener;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListener;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class DefaultDataStoreEventListenerContextTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testTriggeringNullEvent() {
DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext();
context.trigger(null);
}
@Test
public void testExactEventType() {
final AfterInsertEventListener first = new AfterInsertEventListener();
final AfterInsertEventListener second = new AfterInsertEventListener();
final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null);
final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext();
context.register(first);
context.register(second);
context.trigger(event);
assertThat(first.getEvents(), hasSize(1));
assertThat(first.getEvents().get(0), is(event));
assertThat(second.getEvents(), hasSize(1));
assertThat(second.getEvents().get(0), is(event));
}
@Test
public void testParentEventType() {
final AllCatchingEventListener first = new AllCatchingEventListener();
final AfterInsertEventListener second = new AfterInsertEventListener();
final AfterInsertDataStoreEvent event = new AfterInsertDataStoreEvent(null, null, null);
final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext();
context.register(first);
context.register(second);
context.trigger(event);
assertThat(first.getEvents(), hasSize(1));
assertThat(first.getEvents().get(0), Matchers.is(event));
assertThat(second.getEvents(), hasSize(1));
assertThat(second.getEvents().get(0), is(event));
}
@Test
public void testEventPropagation() {
final AfterInsertDataStoreEvent firstEvent = new AfterInsertDataStoreEvent(null, null, null);
final AfterInsertDataStoreEvent secondEvent = new AfterInsertDataStoreEvent(null, null, null);
final AfterInsertEventListener first = new AfterInsertEventListener();
final AfterInsertEventListener second = new AfterInsertEventListener();
final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext();
final DefaultDataStoreEventListenerContext child =
new DefaultDataStoreEventListenerContext(parent);
parent.register(first);
child.register(second);
child.trigger(firstEvent);
parent.trigger(secondEvent);
assertThat(first.getEvents(), hasSize(2));
assertThat(first.getEvents(), contains(firstEvent, secondEvent));
assertThat(second.getEvents(), hasSize(1));
assertThat(second.getEvents().get(0), is(firstEvent));
}
@Test
public void testFindingEventListeners() {
final AfterInsertEventListener first = new AfterInsertEventListener();
final AfterInsertEventListener second = new AfterInsertEventListener();
final DefaultDataStoreEventListenerContext parent = new DefaultDataStoreEventListenerContext();
final DefaultDataStoreEventListenerContext child =
new DefaultDataStoreEventListenerContext(parent);
parent.register(first);
child.register(second);
assertThat(parent.getListeners(AfterInsertDataStoreEvent.class), hasSize(1));
assertThat(
parent.getListeners(AfterInsertDataStoreEvent.class).get(0),
Matchers.<DataStoreEventListener>is(first));
assertThat(child.getListeners(AfterInsertDataStoreEvent.class), hasSize(2));
assertThat(
child.getListeners(AfterInsertDataStoreEvent.class).get(0),
Matchers.<DataStoreEventListener>is(second));
assertThat(
child.getListeners(AfterInsertDataStoreEvent.class).get(1),
Matchers.<DataStoreEventListener>is(first));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/SmartDataStoreEventListenerTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.sample.mocks.AllCatchingEventListener;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingEventListener;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class SmartDataStoreEventListenerTest {
@Test
public void testEventTypeRecognition() {
final SmartDataStoreEventListener<DataStoreEvent> listener =
new SmartDataStoreEventListener<>(new AllCatchingEventListener());
assertThat(listener.getEventType(), is(notNullValue()));
assertThat(listener.getEventType(), is(equalTo(DataStoreEvent.class)));
}
@Test
public void testEventDelegation() {
final SpyingEventListener<DataStoreEvent> spy = new AllCatchingEventListener();
final SmartDataStoreEventListener<DataStoreEvent> listener =
new SmartDataStoreEventListener<>(spy);
final AfterDeleteDataStoreEvent first = new AfterDeleteDataStoreEvent(null, null, null);
final BeforeInsertDataStoreEvent second = new BeforeInsertDataStoreEvent(null, null, null);
listener.onEvent(first);
listener.onEvent(second);
final List<DataStoreEvent> events = spy.getEvents();
assertThat(events, hasSize(2));
assertThat(events.get(0), Matchers.is(first));
assertThat(events.get(1), Matchers.is(second));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditableWrapperTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithCreatedBy;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithCreatedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithDateTimeLastModifiedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithFinalCreatedBy;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithLastModifiedBy;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithSqlDateLastModifiedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithTimeLastModifiedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithTimestampDateLastModifiedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithUtilDateLastModifiedDate;
import com.mmnaseri.utils.spring.data.sample.models.EntityWithWriteOnlyCreatedBy;
import com.mmnaseri.utils.spring.data.sample.usecases.store.SampleAuditorAware;
import org.springframework.data.domain.AuditorAware;
import org.springframework.util.ReflectionUtils;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Field;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Objects;
import java.util.Optional;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
@SuppressWarnings("WeakerAccess, unused")
public class AuditableWrapperTest {
private AuditorAware<?> auditorAware;
@BeforeMethod
public void setUp() {
auditorAware = new SampleAuditorAware();
}
@Test
public void testCreatedBy() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id");
final EntityWithCreatedBy entity = new EntityWithCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(entity.getCreatedBy(), is(nullValue()));
assertThat(wrapper.getCreatedBy(), is(Optional.empty()));
assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true));
wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get());
assertThat(wrapper.getCreatedBy().isPresent(), is(true));
assertThat(wrapper.getCreatedBy().get(), is(SampleAuditorAware.AUDITOR));
assertThat(entity.getCreatedBy(), is(SampleAuditorAware.AUDITOR));
}
@Test
public void testLastModifiedBy() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithLastModifiedBy.class, null, "id");
final EntityWithLastModifiedBy entity = new EntityWithLastModifiedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(entity.getLastModifiedBy(), is(nullValue()));
assertThat(wrapper.getLastModifiedBy(), is(Optional.empty()));
assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true));
wrapper.setLastModifiedBy(auditorAware.getCurrentAuditor().get());
assertThat(wrapper.getLastModifiedBy().isPresent(), is(true));
assertThat(wrapper.getLastModifiedBy().get(), is(SampleAuditorAware.AUDITOR));
assertThat(entity.getLastModifiedBy(), is(SampleAuditorAware.AUDITOR));
}
@Test
public void testCreatedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithCreatedDate.class, null, "id");
final EntityWithCreatedDate entity = new EntityWithCreatedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(entity.getCreatedDate(), is(nullValue()));
assertThat(wrapper.getCreatedDate(), is(Optional.empty()));
final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS);
wrapper.setCreatedDate(time);
assertThat(wrapper.getCreatedDate().isPresent(), is(true));
assertThat(wrapper.getCreatedDate().get(), is(time));
assertThat(entity.getCreatedDate().toInstant(), is(time));
}
@Test
public void testUtilDateLastModifiedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithUtilDateLastModifiedDate.class, null, "id");
final EntityWithUtilDateLastModifiedDate entity = new EntityWithUtilDateLastModifiedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS);
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(wrapper.getLastModifiedDate(), is(Optional.empty()));
wrapper.setLastModifiedDate(time);
assertThat(wrapper.getLastModifiedDate().isPresent(), is(true));
assertThat(wrapper.getLastModifiedDate().get(), is(time));
assertThat(entity.getLastModifiedDate().toInstant(), is(time));
}
@Test
public void testSqlDateLastModifiedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithSqlDateLastModifiedDate.class, null, "id");
final EntityWithSqlDateLastModifiedDate entity = new EntityWithSqlDateLastModifiedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS);
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(wrapper.getLastModifiedDate(), is(Optional.empty()));
wrapper.setLastModifiedDate(time);
assertThat(wrapper.getLastModifiedDate().isPresent(), is(true));
assertThat(wrapper.getLastModifiedDate().get(), is(time));
assertThat(entity.getLastModifiedDate().getTime(), is(time.toEpochMilli()));
}
@Test
public void testTimestampLastModifiedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithTimestampDateLastModifiedDate.class, null, "id");
final EntityWithTimestampDateLastModifiedDate entity =
new EntityWithTimestampDateLastModifiedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS);
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(wrapper.getLastModifiedDate(), is(Optional.empty()));
wrapper.setLastModifiedDate(time);
assertThat(wrapper.getLastModifiedDate().isPresent(), is(true));
assertThat(wrapper.getLastModifiedDate().get(), is(time));
assertThat(entity.getLastModifiedDate(), is(new Timestamp(time.toEpochMilli())));
}
@Test
public void testTimeLastModifiedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithTimeLastModifiedDate.class, null, "id");
final EntityWithTimeLastModifiedDate entity = new EntityWithTimeLastModifiedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Instant time = Instant.now().truncatedTo(ChronoUnit.MILLIS);
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(wrapper.getLastModifiedDate(), is(Optional.empty()));
wrapper.setLastModifiedDate(time);
assertThat(wrapper.getLastModifiedDate().isPresent(), is(true));
assertThat(wrapper.getLastModifiedDate().get(), is(time));
assertThat(entity.getLastModifiedDate(), is(new Time(time.toEpochMilli())));
}
@Test
public void testDateTimeLastModifiedDate() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithDateTimeLastModifiedDate.class, null, "id");
final EntityWithDateTimeLastModifiedDate entity = new EntityWithDateTimeLastModifiedDate();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Instant time = Instant.now();
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(wrapper.getLastModifiedDate(), is(Optional.empty()));
wrapper.setLastModifiedDate(time);
assertThat(wrapper.getLastModifiedDate().isPresent(), is(true));
assertThat(wrapper.getLastModifiedDate().get(), is(time));
assertThat(entity.getLastModifiedDate(), is(time));
}
@Test
public void testSettingNullValue() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id");
final EntityWithCreatedBy entity = new EntityWithCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(entity.getCreatedBy(), is(nullValue()));
//noinspection ConstantConditions
wrapper.setCreatedBy(null);
assertThat(entity.getCreatedBy(), is(nullValue()));
}
@Test
public void testGettingIdentifier() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id");
final EntityWithCreatedBy entity = new EntityWithCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(wrapper.getId(), is(nullValue()));
entity.setId("some identifier");
assertThat(wrapper.getId(), is(notNullValue()));
assertThat(wrapper.getId(), is(entity.getId()));
}
@Test
public void testDirtyChecking() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithCreatedBy.class, null, "id");
final EntityWithCreatedBy entity = new EntityWithCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(wrapper.isNew(), is(true));
entity.setId("some identifier");
assertThat(wrapper.isNew(), is(false));
}
@Test
public void testSettingReadOnlyProperty() {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, EntityWithFinalCreatedBy.class, null, "id");
final EntityWithFinalCreatedBy entity = new EntityWithFinalCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
assertThat(entity.getCreatedBy(), is(nullValue()));
assertThat(wrapper.getCreatedBy(), is(Optional.empty()));
wrapper.setCreatedBy(auditorAware.getCurrentAuditor());
assertThat(wrapper.getCreatedBy(), is(Optional.empty()));
assertThat(entity.getCreatedBy(), is(nullValue()));
}
@Test
public void testWriteOnlyCreatedBy() throws Exception {
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, EntityWithWriteOnlyCreatedBy.class, null, "id");
final EntityWithWriteOnlyCreatedBy entity = new EntityWithWriteOnlyCreatedBy();
final AuditableWrapper wrapper = new AuditableWrapper(entity, repositoryMetadata);
final Field createdBy =
ReflectionUtils.findField(EntityWithWriteOnlyCreatedBy.class, "createdBy");
Objects.requireNonNull(createdBy).setAccessible(true);
assertThat(createdBy.get(entity), is(nullValue()));
assertThat(wrapper.getCreatedBy(), is(Optional.empty()));
assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true));
wrapper.setCreatedBy(auditorAware.getCurrentAuditor().get());
// the wrapper will not be able to read the value ...
assertThat(wrapper.getCreatedBy(), is(Optional.empty()));
// ... but the value is set anyway
assertThat(createdBy.get(entity), is(SampleAuditorAware.AUDITOR));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/DefaultDataStoreRegistryTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.error.DataStoreNotFoundException;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class DefaultDataStoreRegistryTest {
@Test
public void testRegisteringDataStore() {
final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry();
final MemoryDataStore<Object, Person> dataStore = new MemoryDataStore<>(Person.class);
registry.register(dataStore);
assertThat(registry.getDataStore(Person.class), Matchers.is(dataStore));
}
@Test
public void testOverridingDataStore() {
final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry();
final MemoryDataStore<Object, Person> first = new MemoryDataStore<>(Person.class);
final MemoryDataStore<Object, Person> second = new MemoryDataStore<>(Person.class);
registry.register(first);
registry.register(second);
assertThat(registry.getDataStore(Person.class), Matchers.is(second));
}
@Test(expectedExceptions = DataStoreNotFoundException.class)
public void testLookingForInvalidDataStore() {
final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry();
registry.getDataStore(Person.class);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/AuditDataEventListenerTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.sample.models.AuditableEntity;
import com.mmnaseri.utils.spring.data.sample.models.ImplicitlyAuditableEntity;
import com.mmnaseri.utils.spring.data.sample.usecases.store.SampleAuditorAware;
import org.testng.annotations.Test;
import java.util.Date;
import java.util.Optional;
import static com.mmnaseri.utils.spring.data.sample.usecases.store.SampleAuditorAware.AUDITOR;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
public class AuditDataEventListenerTest {
@Test
public void testBeforeInsertForImplicitAuditing() {
final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware());
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, ImplicitlyAuditableEntity.class, null, "id");
final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity();
final Date before = new Date();
listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity));
final Date after = new Date();
assertThat(entity.getCreatedBy(), is(notNullValue()));
assertThat(entity.getCreatedBy(), is(AUDITOR));
assertThat(entity.getCreatedDate(), is(notNullValue()));
assertThat(entity.getCreatedDate().getTime(), is(greaterThanOrEqualTo(before.getTime())));
assertThat(entity.getCreatedDate().getTime(), is(lessThanOrEqualTo(after.getTime())));
assertThat(entity.getLastModifiedDate(), is(nullValue()));
assertThat(entity.getLastModifiedBy(), is(nullValue()));
}
@Test
public void testBeforeUpdateForImplicitAuditing() {
final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware());
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, ImplicitlyAuditableEntity.class, null, "id");
final ImplicitlyAuditableEntity entity = new ImplicitlyAuditableEntity();
final Date before = new Date();
listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity));
final Date after = new Date();
assertThat(entity.getLastModifiedBy(), is(notNullValue()));
assertThat(entity.getLastModifiedBy(), is(AUDITOR));
assertThat(entity.getLastModifiedDate(), is(notNullValue()));
assertThat(entity.getLastModifiedDate().getTime(), is(greaterThanOrEqualTo(before.getTime())));
assertThat(entity.getLastModifiedDate().getTime(), is(lessThanOrEqualTo(after.getTime())));
assertThat(entity.getCreatedDate(), is(nullValue()));
assertThat(entity.getCreatedBy(), is(nullValue()));
}
@Test
public void testBeforeInsertForExplicitAuditing() {
final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware());
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, AuditableEntity.class, null, "id");
final AuditableEntity entity = new AuditableEntity();
final Date before = new Date();
listener.onEvent(new BeforeInsertDataStoreEvent(repositoryMetadata, null, entity));
final Date after = new Date();
assertThat(entity.getCreatedBy().isPresent(), is(true));
assertThat(entity.getCreatedBy().get(), is(notNullValue()));
assertThat(entity.getCreatedBy().get(), is(AUDITOR));
assertThat(entity.getCreatedDate().isPresent(), is(true));
assertThat(entity.getCreatedDate().get(), is(notNullValue()));
assertThat(
entity.getCreatedDate().get().toEpochMilli(), is(greaterThanOrEqualTo(before.getTime())));
assertThat(
entity.getCreatedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime())));
assertThat(entity.getLastModifiedDate(), is(Optional.empty()));
assertThat(entity.getLastModifiedBy(), is(Optional.empty()));
}
@Test
public void testBeforeUpdateForExplicitAuditing() {
final AuditDataEventListener listener = new AuditDataEventListener(new SampleAuditorAware());
final RepositoryMetadata repositoryMetadata =
new ImmutableRepositoryMetadata(String.class, AuditableEntity.class, null, "id");
final AuditableEntity entity = new AuditableEntity();
final Date before = new Date();
listener.onEvent(new BeforeUpdateDataStoreEvent(repositoryMetadata, null, entity));
final Date after = new Date();
assertThat(entity.getLastModifiedBy().isPresent(), is(true));
assertThat(entity.getLastModifiedBy().get(), is(notNullValue()));
assertThat(entity.getLastModifiedBy().get(), is(AUDITOR));
assertThat(entity.getLastModifiedDate().isPresent(), is(true));
assertThat(entity.getLastModifiedDate().get(), is(notNullValue()));
assertThat(
entity.getLastModifiedDate().get().toEpochMilli(),
is(greaterThanOrEqualTo(before.getTime())));
assertThat(
entity.getLastModifiedDate().get().toEpochMilli(), is(lessThanOrEqualTo(after.getTime())));
assertThat(entity.getCreatedDate(), is(Optional.empty()));
assertThat(entity.getCreatedBy(), is(Optional.empty()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/store/impl/EventPublishingDataStoreTest.java | package com.mmnaseri.utils.spring.data.store.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableRepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.CorruptDataException;
import com.mmnaseri.utils.spring.data.sample.mocks.EventTrigger;
import com.mmnaseri.utils.spring.data.sample.mocks.Operation;
import com.mmnaseri.utils.spring.data.sample.mocks.OperationRequest;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataStore;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingListenerContext;
import com.mmnaseri.utils.spring.data.sample.models.DummyEvent;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import com.mmnaseri.utils.spring.data.store.DataStore;
import org.hamcrest.Matchers;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/9/16)
*/
@SuppressWarnings("WeakerAccess")
public class EventPublishingDataStoreTest {
private static final AtomicLong counter = new AtomicLong(0);
private RepositoryMetadata repositoryMetadata;
private DataStore<String, Person> delegate;
private SpyingDataStore<String, Person> delegateSpy;
private DataStore<String, Person> dataStore;
private SpyingListenerContext listenerContext;
@BeforeMethod
public void setUp() {
repositoryMetadata =
new ImmutableRepositoryMetadata(
String.class, Person.class, SimplePersonRepository.class, "id");
listenerContext = new SpyingListenerContext(counter);
delegate = new MemoryDataStore<>(Person.class);
delegateSpy = new SpyingDataStore<>(delegate, counter);
dataStore = new EventPublishingDataStore<>(delegateSpy, repositoryMetadata, listenerContext);
}
@Test
public void testHasKeyDelegation() {
final String key = "1";
delegate.save(key, new Person());
assertThat(dataStore.hasKey(key), is(true));
}
@Test
public void testRetrieveDelegation() {
final String key = "key";
assertThat(dataStore.retrieve(key), is(delegate.retrieve(key)));
delegate.save(key, new Person());
assertThat(dataStore.retrieve(key), is(delegate.retrieve(key)));
}
@Test
public void testRetrieveAllDelegation() {
final String k1 = "k1";
final String k2 = "k2";
assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll()));
delegate.save(k1, new Person());
delegate.save(k2, new Person());
assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll()));
}
@Test
public void testEntityTypeDelegation() {
assertThat(dataStore.getEntityType(), Matchers.<Class<Person>>is(delegate.getEntityType()));
}
@Test
public void testEventPublishingDelegation() {
final DummyEvent event = new DummyEvent();
((EventPublishingDataStore) dataStore).publishEvent(event);
assertThat(listenerContext.getEvents(), hasSize(1));
assertThat(listenerContext.getEvents().get(0).getEvent(), Matchers.is(event));
}
@Test
public void testKeysDelegation() {
final AtomicBoolean called = new AtomicBoolean(false);
final DataStore<String, Person> localDataStore =
new EventPublishingDataStore<>(
new MemoryDataStore<String, Person>(Person.class) {
@Override
public Collection<String> keys() {
called.set(true);
return super.keys();
}
},
repositoryMetadata,
listenerContext);
assertThat(called.get(), is(false));
localDataStore.keys();
assertThat(called.get(), is(true));
}
@Test(expectedExceptions = CorruptDataException.class)
public void testSavingNullKey() {
dataStore.save(null, new Person());
}
@Test(expectedExceptions = CorruptDataException.class)
public void testSavingNullEntity() {
dataStore.save("", null);
}
@Test
public void testInsert() {
final String key = "k";
final Person entity = new Person();
dataStore.save(key, entity);
assertThat(listenerContext.getEvents(), hasSize(2));
assertThat(
listenerContext.getEvents().get(0).getEvent(),
is(instanceOf(BeforeInsertDataStoreEvent.class)));
assertThat(
listenerContext.getEvents().get(1).getEvent(),
is(instanceOf(AfterInsertDataStoreEvent.class)));
assertThat(delegateSpy.getRequests(), hasSize(2));
final OperationRequest save = delegateSpy.getRequests().get(1);
assertThat(save.getOperation(), is(Operation.SAVE));
assertThat(save.getKey(), Matchers.is(key));
assertThat(save.getEntity(), Matchers.is(entity));
final EventTrigger before = listenerContext.getEvents().get(0);
final EventTrigger after = listenerContext.getEvents().get(1);
assertThat(before.getTimestamp(), is(lessThan(save.getTimestamp())));
assertThat(save.getTimestamp(), is(lessThan(after.getTimestamp())));
assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore));
assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore));
}
@Test
public void testUpdate() {
final String key = "k";
final Person entity = new Person();
dataStore.save(key, entity);
listenerContext.reset();
delegateSpy.reset();
dataStore.save(key, entity);
assertThat(listenerContext.getEvents(), hasSize(2));
assertThat(
listenerContext.getEvents().get(0).getEvent(),
is(instanceOf(BeforeUpdateDataStoreEvent.class)));
assertThat(
listenerContext.getEvents().get(1).getEvent(),
is(instanceOf(AfterUpdateDataStoreEvent.class)));
assertThat(delegateSpy.getRequests(), hasSize(2));
final OperationRequest request = delegateSpy.getRequests().get(1);
assertThat(request.getOperation(), is(Operation.SAVE));
assertThat(request.getKey(), Matchers.is(key));
assertThat(request.getEntity(), Matchers.is(entity));
final EventTrigger before = listenerContext.getEvents().get(0);
final EventTrigger after = listenerContext.getEvents().get(1);
assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp())));
assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp())));
assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore));
assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore));
}
@Test
public void testDeletingNonExistentKey() {
dataStore.delete("key");
assertThat(delegateSpy.getRequests(), hasSize(1));
assertThat(listenerContext.getEvents(), is(Matchers.empty()));
}
@Test
public void testDelete() {
final String key = "k";
final Person entity = new Person();
dataStore.save(key, entity);
listenerContext.reset();
delegateSpy.reset();
dataStore.delete(key);
assertThat(listenerContext.getEvents(), hasSize(2));
assertThat(
listenerContext.getEvents().get(0).getEvent(),
is(instanceOf(BeforeDeleteDataStoreEvent.class)));
assertThat(
listenerContext.getEvents().get(1).getEvent(),
is(instanceOf(AfterDeleteDataStoreEvent.class)));
assertThat(delegateSpy.getRequests(), hasSize(3));
final OperationRequest request = delegateSpy.getRequests().get(2);
assertThat(request.getOperation(), is(Operation.DELETE));
assertThat(request.getKey(), Matchers.is(key));
assertThat(request.getEntity(), is(nullValue()));
final EventTrigger before = listenerContext.getEvents().get(0);
final EventTrigger after = listenerContext.getEvents().get(1);
assertThat(before.getTimestamp(), is(lessThan(request.getTimestamp())));
assertThat(request.getTimestamp(), is(lessThan(after.getTimestamp())));
assertThat(before.getEvent().getDataStore(), Matchers.is(dataStore));
assertThat(after.getEvent().getDataStore(), Matchers.is(dataStore));
}
@Test
public void testTruncating() {
final String k1 = "k1";
final String k2 = "k2";
assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll()));
delegate.save(k1, new Person());
delegate.save(k2, new Person());
assertThat(dataStore.retrieveAll(), is(delegate.retrieveAll()));
dataStore.truncate();
assertThat(delegate.retrieveAll(), is(Matchers.empty()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/mock/RepositoryMockBuilderTest.java | package com.mmnaseri.utils.spring.data.dsl.mock;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.RepositoryAware;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultRepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.domain.impl.key.NoOpKeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator;
import com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder;
import com.mmnaseri.utils.spring.data.error.CorruptDataException;
import com.mmnaseri.utils.spring.data.error.DataOperationExecutionException;
import com.mmnaseri.utils.spring.data.error.MockBuilderException;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfigurationAware;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultTypeMappingContext;
import com.mmnaseri.utils.spring.data.proxy.impl.NonDataOperationInvocationHandler;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.sample.mocks.CustomStringKeyGenerator;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.SimpleCrudPersonRepository;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.InformationExposingRepository;
import com.mmnaseri.utils.spring.data.sample.usecases.proxy.InformationExposingRepositoryFactory;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/11/16, 2:38 PM)
*/
@SuppressWarnings("unused")
public class RepositoryMockBuilderTest {
@Test
public void testOutOfTheBoxMocking() {
final SimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.useConfiguration(RepositoryFactoryBuilder.defaultConfiguration())
.mock(SimpleCrudPersonRepository.class);
assertThat(repository, is(notNullValue()));
final Person person = repository.save(new Person());
assertThat(repository.findAll(), is(notNullValue()));
assertThat(repository.findAll(), hasSize(1));
assertThat(repository.findAll(), hasItem(person));
repository.delete(person);
assertThat(repository.findAll(), is(empty()));
}
@Test
public void testEqualityOfMocks() {
assertThat(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class), is(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class)));
assertThat(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class).hashCode(), is(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class).hashCode()));
assertThat(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class).toString(), is(new RepositoryMockBuilder().mock(SimpleCrudPersonRepository.class).toString()));
}
@Test
public void testMockingWithoutKeyGeneration() {
final SimpleCrudPersonRepository repository =
new RepositoryMockBuilder().withoutGeneratingKeys().mock(SimpleCrudPersonRepository.class);
assertThat(repository, is(notNullValue()));
boolean exceptionThrown = false;
try {
repository.save(new Person());
} catch (Exception e) {
assertThat(e, is(instanceOf(DataOperationExecutionException.class)));
assertThat(e.getCause(), is(notNullValue()));
assertThat(e.getCause(), is(instanceOf(CorruptDataException.class)));
exceptionThrown = true;
}
assertThat(exceptionThrown, is(true));
final Person person = repository.save(new Person().setId("1"));
assertThat(repository.findAll(), is(notNullValue()));
assertThat(repository.findAll(), hasSize(1));
assertThat(repository.findAll(), hasItem(person));
repository.delete(person);
assertThat(repository.findAll(), is(empty()));
}
@Test
public void testMockingWithFallbackKeyGenerator() {
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration(RepositoryFactoryBuilder.defaultConfiguration());
configuration.setDefaultKeyGenerator(new UUIDKeyGenerator());
final SimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.useConfiguration(configuration)
.mock(SimpleCrudPersonRepository.class);
assertThat(repository, is(notNullValue()));
final Person saved = repository.save(new Person());
assertThat(saved, is(notNullValue()));
assertThat(saved.getId(), is(notNullValue()));
}
@Test
public void testCustomKeyGeneration() {
final SimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.generateKeysUsing(CustomStringKeyGenerator.class)
.mock(SimpleCrudPersonRepository.class);
assertThat(repository, is(notNullValue()));
final Person person = repository.save(new Person());
assertThat(repository.findAll(), is(notNullValue()));
assertThat(repository.findAll(), hasSize(1));
assertThat(repository.findAll(), hasItem(person));
repository.delete(person);
assertThat(repository.findAll(), is(empty()));
}
@Test(expectedExceptions = MockBuilderException.class)
public void testUsingInvalidKeyGenerator() {
new RepositoryMockBuilder().generateKeysUsing(InaccessibleKeyGenerator.class);
}
@Test
public void testUsingCustomImplementations() {
final MappedSimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.usingImplementation(ValueHashMapper.class)
.and(ValueStringMapper.class)
.mock(MappedSimpleCrudPersonRepository.class);
assertThat(repository, is(notNullValue()));
final Person person = repository.save(new Person());
assertThat(repository.findAll(), is(notNullValue()));
assertThat(repository.findAll(), hasSize(1));
assertThat(repository.findAll(), hasItem(person));
repository.delete(person);
assertThat(repository.findAll(), is(empty()));
assertThat(repository.getHash(), is(repository.hashCode()));
assertThat(repository.getString(), is(repository.toString()));
}
/**
* This is a slightly more sophisticated test that adds additional methods to the interface being
* mocked.
*
* <p>This sort of thing might come in handy if we are unsure of how to proceed with the tests, or
* if there is something we need bound to the repository specifically for the tests, however, it
* should be noted that adding functionality to your repositories for the purpose of testing is
* not really the greatest idea.
*/
@Test
public void testUsingCustomFactory() {
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration();
configuration.setDataStoreRegistry(new DefaultDataStoreRegistry());
configuration.setDescriptionExtractor(
new MethodQueryDescriptionExtractor(new DefaultOperatorContext()));
configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext());
configuration.setFunctionRegistry(new DefaultDataFunctionRegistry());
configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler());
configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver());
configuration.setResultAdapterContext(new DefaultResultAdapterContext());
configuration.setTypeMappingContext(new DefaultTypeMappingContext());
final SimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.useFactory(new InformationExposingRepositoryFactory(configuration))
.mock(SimpleCrudPersonRepository.class);
assertThat(repository, is(instanceOf(InformationExposingRepository.class)));
final InformationExposingRepository informationExposingRepository =
(InformationExposingRepository) repository;
assertThat(informationExposingRepository.getFactoryConfiguration(), is(notNullValue()));
assertThat(informationExposingRepository.getFactoryConfiguration(), Matchers.is(configuration));
assertThat(informationExposingRepository.getConfiguration(), is(notNullValue()));
assertThat(
informationExposingRepository.getConfiguration().getBoundImplementations(),
is(notNullValue()));
assertThat(
informationExposingRepository.getConfiguration().getBoundImplementations(), is(empty()));
assertThat(
informationExposingRepository.getConfiguration().getKeyGenerator(), is(notNullValue()));
assertThat(
informationExposingRepository.getConfiguration().getRepositoryMetadata(),
is(notNullValue()));
assertThat(
informationExposingRepository.getConfiguration().getRepositoryMetadata().getEntityType(),
is(Matchers.equalTo(Person.class)));
assertThat(
informationExposingRepository
.getConfiguration()
.getRepositoryMetadata()
.getIdentifierType(),
is(Matchers.equalTo(String.class)));
assertThat(
informationExposingRepository
.getConfiguration()
.getRepositoryMetadata()
.getRepositoryInterface(),
is(Matchers.equalTo(SimpleCrudPersonRepository.class)));
assertThat(
informationExposingRepository
.getConfiguration()
.getRepositoryMetadata()
.getIdentifierProperty(),
is("id"));
}
@Test
public void testUsingCustomConfiguration() {
final DefaultTypeMappingContext mappingContext = new DefaultTypeMappingContext();
mappingContext.register(
ConfiguredSimpleCrudPersonRepository.class, ConfigurationAwareMapper.class);
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration();
configuration.setDataStoreRegistry(new DefaultDataStoreRegistry());
configuration.setDescriptionExtractor(
new MethodQueryDescriptionExtractor(new DefaultOperatorContext()));
configuration.setEventListenerContext(new DefaultDataStoreEventListenerContext());
configuration.setFunctionRegistry(new DefaultDataFunctionRegistry());
configuration.setOperationInvocationHandler(new NonDataOperationInvocationHandler());
configuration.setRepositoryMetadataResolver(new DefaultRepositoryMetadataResolver());
configuration.setResultAdapterContext(new DefaultResultAdapterContext());
configuration.setTypeMappingContext(mappingContext);
final ConfiguredSimpleCrudPersonRepository repository =
new RepositoryMockBuilder()
.useConfiguration(configuration)
.mock(ConfiguredSimpleCrudPersonRepository.class);
assertThat(repository.getConfiguration(), is(notNullValue()));
assertThat(repository.getConfiguration(), Matchers.is(configuration));
}
@Test
public void testNoOpKeyGeneration() {
final NoOpKeyGenerator<Object> generator = new NoOpKeyGenerator<>();
assertThat(generator.generate(), is(nullValue()));
}
public interface MappedSimpleCrudPersonRepository extends SimpleCrudPersonRepository {
int getHash();
String getString();
}
public interface ConfiguredSimpleCrudPersonRepository extends SimpleCrudPersonRepository {
RepositoryFactoryConfiguration getConfiguration();
}
public static class ValueHashMapper implements RepositoryAware<MappedSimpleCrudPersonRepository> {
private MappedSimpleCrudPersonRepository repository;
@Override
public void setRepository(MappedSimpleCrudPersonRepository repository) {
this.repository = repository;
}
public int getHash() {
return repository.hashCode();
}
}
public static class ValueStringMapper
implements RepositoryAware<MappedSimpleCrudPersonRepository> {
private MappedSimpleCrudPersonRepository repository;
@Override
public void setRepository(MappedSimpleCrudPersonRepository repository) {
this.repository = repository;
}
public String getString() {
return repository.toString();
}
}
public static class ConfigurationAwareMapper implements RepositoryFactoryConfigurationAware {
private RepositoryFactoryConfiguration configuration;
@Override
public void setRepositoryFactoryConfiguration(RepositoryFactoryConfiguration configuration) {
this.configuration = configuration;
}
public RepositoryFactoryConfiguration getConfiguration() {
return configuration;
}
}
public static class InaccessibleKeyGenerator implements KeyGenerator<Object> {
private InaccessibleKeyGenerator() {}
@Override
public Object generate() {
return null;
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/dsl/factory/RepositoryFactoryBuilderTest.java | package com.mmnaseri.utils.spring.data.dsl.factory;
import com.mmnaseri.utils.spring.data.domain.Operator;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultOperatorContext;
import com.mmnaseri.utils.spring.data.domain.impl.DefaultRepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableOperator;
import com.mmnaseri.utils.spring.data.domain.impl.MethodQueryDescriptionExtractor;
import com.mmnaseri.utils.spring.data.domain.impl.key.NoOpKeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactory;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultResultAdapterContext;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultTypeMappingContext;
import com.mmnaseri.utils.spring.data.proxy.impl.NonDataOperationInvocationHandler;
import com.mmnaseri.utils.spring.data.proxy.impl.adapters.VoidResultAdapter;
import com.mmnaseri.utils.spring.data.query.DataFunction;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.sample.mocks.AllCatchingEventListener;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataFunction;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingHandler;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.ConfiguredMapping;
import com.mmnaseri.utils.spring.data.sample.repositories.ConfiguredSimplePersonRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.ExtendedSimplePersonRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.JpaPersonRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.NumberMapping;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.StringMapping;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreEvent;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListener;
import com.mmnaseri.utils.spring.data.store.DataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.AuditDataEventListener;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreEventListenerContext;
import com.mmnaseri.utils.spring.data.store.impl.DefaultDataStoreRegistry;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.hamcrest.Matchers;
import org.springframework.data.domain.AuditorAware;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.List;
import static com.mmnaseri.utils.spring.data.dsl.factory.RepositoryFactoryBuilder.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/12/16, 11:42 AM)
*/
public class RepositoryFactoryBuilderTest {
@Test
public void testDefaultConfiguration() {
final RepositoryFactoryConfiguration configuration =
RepositoryFactoryBuilder.defaultConfiguration();
assertThat(configuration, is(notNullValue()));
assertThat(configuration.getDataStoreRegistry(), is(notNullValue()));
assertThat(configuration.getTypeMappingContext(), is(notNullValue()));
assertThat(configuration.getResultAdapterContext(), is(notNullValue()));
assertThat(configuration.getRepositoryMetadataResolver(), is(notNullValue()));
assertThat(configuration.getOperationInvocationHandler(), is(notNullValue()));
assertThat(configuration.getFunctionRegistry(), is(notNullValue()));
assertThat(configuration.getEventListenerContext(), is(notNullValue()));
assertThat(configuration.getDescriptionExtractor(), is(notNullValue()));
}
@Test
public void testDefaultFactory() {
final RepositoryFactory factory = RepositoryFactoryBuilder.defaultFactory();
assertThat(factory, is(notNullValue()));
}
@Test
public void testConfiguringAProvidedConfiguration() {
final DefaultRepositoryFactoryConfiguration configuration =
new DefaultRepositoryFactoryConfiguration();
final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry();
configuration.setFunctionRegistry(functionRegistry);
configuration.setDefaultKeyGenerator(new NoOpKeyGenerator<>());
final UUIDKeyGenerator keyGenerator = new UUIDKeyGenerator();
final RepositoryFactoryConfiguration modifiedConfiguration =
given(configuration)
.withDefaultKeyGenerator(keyGenerator)
.withListener(new AllCatchingEventListener())
.configure();
assertThat(modifiedConfiguration, is(notNullValue()));
assertThat(modifiedConfiguration.getDefaultKeyGenerator(), is((Object) keyGenerator));
assertThat(modifiedConfiguration.getEventListenerContext(), is(notNullValue()));
assertThat(
modifiedConfiguration.getEventListenerContext().getListeners(DataStoreEvent.class),
hasSize(1));
}
@Test
public void testUsingCustomMetadataResolver() {
final DefaultRepositoryMetadataResolver resolver = new DefaultRepositoryMetadataResolver();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().resolveMetadataUsing(resolver).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), is(notNullValue()));
assertThat(factory.getConfiguration().getRepositoryMetadataResolver(), Matchers.is(resolver));
}
@Test
public void testUsingCustomQueryDescriptor() {
final MethodQueryDescriptionExtractor queryDescriptionExtractor =
new MethodQueryDescriptionExtractor(new DefaultOperatorContext());
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().extractQueriesUsing(queryDescriptionExtractor).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue()));
assertThat(factory.getConfiguration().getDescriptionExtractor(), is(queryDescriptionExtractor));
}
@Test
public void testSpecifyingDefaultKeyGenerator() {
final UUIDKeyGenerator generator = new UUIDKeyGenerator();
final RepositoryFactoryConfiguration configuration =
RepositoryFactoryBuilder.builder().withDefaultKeyGenerator(generator).configure();
assertThat(configuration.getDefaultKeyGenerator(), is(notNullValue()));
assertThat(configuration.getDefaultKeyGenerator(), is((Object) generator));
}
@Test
public void testUsingCustomOperatorContext() {
final DefaultOperatorContext operatorContext = new DefaultOperatorContext();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withOperators(operatorContext).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue()));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext(),
is(notNullValue()));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext(),
Matchers.is(operatorContext));
}
@Test
public void testUsingDefaultOperatorContextWithAdditionalOperators() {
final ImmutableOperator x = new ImmutableOperator("x", 0, null, "X");
final ImmutableOperator y = new ImmutableOperator("y", 0, null, "Y");
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().registerOperator(x).and(y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getDescriptionExtractor(), is(notNullValue()));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext(),
is(notNullValue()));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"),
is(notNullValue()));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("X"),
Matchers.is(x));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"),
is(notNullValue(Operator.class)));
assertThat(
factory.getConfiguration().getDescriptionExtractor().getOperatorContext().getBySuffix("Y"),
Matchers.is(y));
}
@Test
public void testUsingCustomFunctionRegistry() {
final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withDataFunctions(functionRegistry).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue()));
assertThat(factory.getConfiguration().getFunctionRegistry(), Matchers.is(functionRegistry));
}
@Test
public void testUsingDefaultFunctionRegistryWithExtraFunctions() {
final SpyingDataFunction<Object> x = new SpyingDataFunction<>(null);
final SpyingDataFunction<Object> y = new SpyingDataFunction<>(null);
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().registerFunction("x", x).and("y", y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue()));
assertThat(factory.getConfiguration().getFunctionRegistry(), is(notNullValue()));
assertThat(
factory.getConfiguration().getFunctionRegistry().getFunction("x"), is(notNullValue()));
assertThat(
factory.getConfiguration().getFunctionRegistry().getFunction("x"),
Matchers.<DataFunction>is(x));
assertThat(
factory.getConfiguration().getFunctionRegistry().getFunction("y"), is(notNullValue()));
assertThat(
factory.getConfiguration().getFunctionRegistry().getFunction("y"),
Matchers.<DataFunction>is(y));
}
@Test
public void testUsingCustomDataStoreRegistry() {
final DefaultDataStoreRegistry registry = new DefaultDataStoreRegistry();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withDataStores(registry).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue()));
assertThat(factory.getConfiguration().getDataStoreRegistry(), Matchers.is(registry));
}
@Test
public void testUsingDefaultDataStoreRegistryAndCustomDataStores() {
final MemoryDataStore<Object, Integer> x = new MemoryDataStore<>(Integer.class);
final MemoryDataStore<Object, String> y = new MemoryDataStore<>(String.class);
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().registerDataStore(x).and(y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getDataStoreRegistry(), is(notNullValue()));
assertThat(
factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class),
is(notNullValue()));
assertThat(
factory.getConfiguration().getDataStoreRegistry().getDataStore(Integer.class),
Matchers.<DataStore>is(x));
assertThat(
factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class),
is(notNullValue()));
assertThat(
factory.getConfiguration().getDataStoreRegistry().getDataStore(String.class),
Matchers.<DataStore>is(y));
}
@Test
public void testUsingCustomResultAdapterContext() {
final DefaultResultAdapterContext context = new DefaultResultAdapterContext();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withAdapters(context).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue()));
assertThat(factory.getConfiguration().getResultAdapterContext(), Matchers.is(context));
}
@Test
public void testUsingDefaultContextWithCustomAdapters() {
final VoidResultAdapter x = new VoidResultAdapter();
final VoidResultAdapter y = new VoidResultAdapter();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().adaptResultsUsing(x).and(y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getResultAdapterContext(), is(notNullValue()));
assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(x));
assertThat(factory.getConfiguration().getResultAdapterContext().getAdapters(), hasItem(y));
}
@Test
public void testUsingCustomTypeMappingContext() {
final DefaultTypeMappingContext context = new DefaultTypeMappingContext();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withMappings(context).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue()));
assertThat(factory.getConfiguration().getTypeMappingContext(), Matchers.is(context));
}
@Test
public void testUsingDefaultTypeMappingContextAndCustomTypeMappings() {
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder()
.honoringImplementation(Object.class, Integer.class)
.and(Object.class, String.class)
.build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getTypeMappingContext(), is(notNullValue()));
assertThat(
factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class),
hasItem(Integer.class));
assertThat(
factory.getConfiguration().getTypeMappingContext().getImplementations(Object.class),
hasItem(String.class));
}
@Test
public void testUsingCustomOperationHandler() {
final NonDataOperationInvocationHandler handler = new NonDataOperationInvocationHandler();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withOperationHandlers(handler).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue()));
assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(handler));
}
@Test
public void testUsingDefaultOperationHandlerWithCustomOperations() {
final SpyingHandler x = new SpyingHandler();
final SpyingHandler y = new SpyingHandler();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withOperationHandler(x).and(y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getOperationInvocationHandler(), is(notNullValue()));
assertThat(
factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(x));
assertThat(
factory.getConfiguration().getOperationInvocationHandler().getHandlers(), hasItem(y));
}
@Test
public void testUsingCustomEventListenerContext() {
final DefaultDataStoreEventListenerContext context = new DefaultDataStoreEventListenerContext();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withListeners(context).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue()));
assertThat(factory.getConfiguration().getEventListenerContext(), Matchers.is(context));
}
@Test
public void testUsingDefaultEventListenerContextWithCustomListeners() {
final AllCatchingEventListener x = new AllCatchingEventListener();
final AllCatchingEventListener y = new AllCatchingEventListener();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().withListener(x).and(y).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
assertThat(factory.getConfiguration().getEventListenerContext(), is(notNullValue()));
assertThat(
factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class),
hasItem(x));
assertThat(
factory.getConfiguration().getEventListenerContext().getListeners(DataStoreEvent.class),
hasItem(y));
}
@Test
public void testEnablingAuditing() {
final RepositoryFactory factory = RepositoryFactoryBuilder.builder().enableAuditing().build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
final DataStoreEventListenerContext listenerContext =
factory.getConfiguration().getEventListenerContext();
assertThat(listenerContext, is(notNullValue()));
final List<DataStoreEventListener<? extends DataStoreEvent>> listeners =
listenerContext.getListeners(DataStoreEvent.class);
assertThat(listeners, hasSize(1));
assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class)));
}
@Test
public void testEnablingAuditingWithCustomAuditorAware() {
final AuditorAware auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware();
final RepositoryFactory factory =
RepositoryFactoryBuilder.builder().enableAuditing(auditorAware).build();
assertThat(factory, is(notNullValue()));
assertThat(factory.getConfiguration(), is(notNullValue()));
final DataStoreEventListenerContext listenerContext =
factory.getConfiguration().getEventListenerContext();
assertThat(listenerContext, is(notNullValue()));
final List<DataStoreEventListener<? extends DataStoreEvent>> listeners =
listenerContext.getListeners(DataStoreEvent.class);
assertThat(listeners, hasSize(1));
assertThat(listeners.get(0), is(instanceOf(AuditDataEventListener.class)));
final AuditDataEventListener auditDataEventListener = (AuditDataEventListener) listeners.get(0);
final AuditorAware usedAuditorAware = auditDataEventListener.getAuditorAware();
assertThat(usedAuditorAware, is(notNullValue()));
assertThat(usedAuditorAware, is(auditorAware));
}
@Test
public void testDefaultAuditorAware() {
final AuditorAware<String> auditorAware = new RepositoryFactoryBuilder.DefaultAuditorAware();
assertThat(auditorAware.getCurrentAuditor().isPresent(), is(true));
assertThat(auditorAware.getCurrentAuditor().get(), is(RepositoryFactoryBuilder.DEFAULT_USER));
}
@Test
public void testOutOfTheBoxMocking() {
final SimplePersonRepository repository =
RepositoryFactoryBuilder.builder().mock(SimplePersonRepository.class);
assertThat(repository, is(notNullValue()));
}
@Test
public void testMockingUsingCustomImplementation() {
final ExtendedSimplePersonRepository repository =
RepositoryFactoryBuilder.builder()
.usingImplementation(StringMapping.class)
.and(NumberMapping.class)
.mock(ExtendedSimplePersonRepository.class);
assertThat(repository, is(notNullValue()));
assertThat(repository.getString(), is("Hello!"));
assertThat(repository.getNumber(), Matchers.is(123));
}
@Test
public void testMockingWithoutGeneratingKeys() {
final ConfiguredSimplePersonRepository repository =
RepositoryFactoryBuilder.builder()
.withoutGeneratingKeys()
.usingImplementation(ConfiguredMapping.class)
.mock(ConfiguredSimplePersonRepository.class);
assertThat(repository.getRepositoryConfiguration(), is(notNullValue()));
assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue()));
assertThat(
repository.getRepositoryConfiguration().getKeyGenerator(),
is(instanceOf(NoOpKeyGenerator.class)));
}
@Test
public void testMockingWithCustomKeyGeneration() {
final NoOpKeyGenerator<Object> keyGenerator = new NoOpKeyGenerator<>();
final ConfiguredSimplePersonRepository repository =
RepositoryFactoryBuilder.builder()
.generateKeysUsing(keyGenerator)
.usingImplementation(ConfiguredMapping.class)
.mock(ConfiguredSimplePersonRepository.class);
assertThat(repository.getRepositoryConfiguration(), is(notNullValue()));
assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue()));
assertThat(
repository.getRepositoryConfiguration().getKeyGenerator(), Matchers.is(keyGenerator));
}
@Test
public void testMockingWithCustomKeyGenerationByType() {
//noinspection unchecked
final ConfiguredSimplePersonRepository repository =
RepositoryFactoryBuilder.builder()
.generateKeysUsing(NoOpKeyGenerator.class)
.usingImplementation(ConfiguredMapping.class)
.mock(ConfiguredSimplePersonRepository.class);
assertThat(repository.getRepositoryConfiguration(), is(notNullValue()));
assertThat(repository.getRepositoryConfiguration().getKeyGenerator(), is(notNullValue()));
assertThat(
repository.getRepositoryConfiguration().getKeyGenerator(),
is(instanceOf(NoOpKeyGenerator.class)));
}
@Test
public void testSaveIterable() {
final JpaPersonRepository repository =
RepositoryFactoryBuilder.builder().mock(JpaPersonRepository.class);
final Iterable iterable =
Arrays.asList(new Person().setId("1"), new Person().setId("2"), new Person().setId("3"));
repository.saveAll(iterable);
assertThat(repository.findAll(), hasSize(3));
assertThat(repository.findAll(), containsInAnyOrder(((List) iterable).toArray()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SelectDataStoreOperationTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.Parameter;
import com.mmnaseri.utils.spring.data.query.NullHandling;
import com.mmnaseri.utils.spring.data.query.PageParameterExtractor;
import com.mmnaseri.utils.spring.data.query.SortDirection;
import com.mmnaseri.utils.spring.data.query.impl.DefaultQueryDescriptor;
import com.mmnaseri.utils.spring.data.query.impl.ImmutableOrder;
import com.mmnaseri.utils.spring.data.query.impl.ImmutableSort;
import com.mmnaseri.utils.spring.data.query.impl.PageablePageParameterExtractor;
import com.mmnaseri.utils.spring.data.query.impl.WrappedSortParameterExtractor;
import com.mmnaseri.utils.spring.data.sample.models.Address;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.RepositoryWithValidMethods;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.DataStoreOperation;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class SelectDataStoreOperationTest {
private DataStore<String, Person> dataStore;
@BeforeMethod
public void setUp() {
dataStore = new MemoryDataStore<>(Person.class);
dataStore.save(
"k1",
new Person()
.setId("k1")
.setFirstName("Milad")
.setLastName("Naseri")
.setAddress(new Address().setCity("Tehran"))
.setAge(10));
dataStore.save(
"k2",
new Person()
.setId("k2")
.setFirstName("Zohreh")
.setLastName("Sadeghi")
.setAddress(new Address().setCity("Seattle"))
.setAge(12));
dataStore.save(
"k3",
new Person()
.setId("k3")
.setFirstName("Milad")
.setLastName("Naseri")
.setAddress(new Address().setCity("Seattle"))
.setAge(40));
dataStore.save(
"k4",
new Person()
.setId("k4")
.setFirstName("Zohreh")
.setLastName("Sadeghi")
.setAddress(new Address().setCity("Amol"))
.setAge(25));
}
@Test
public void testSimpleSelection() throws Exception {
final List<List<Parameter>> branches = new ArrayList<>();
final DefaultOperatorContext operatorContext = new DefaultOperatorContext();
branches.add(
Arrays.asList(
new ImmutableParameter(
"firstName",
Collections.emptySet(),
new int[] {0},
operatorContext.getBySuffix("Is")),
new ImmutableParameter(
"lastName",
Collections.emptySet(),
new int[] {1},
operatorContext.getBySuffix("Is"))));
branches.add(
Collections.singletonList(
new ImmutableParameter(
"address.city",
Collections.emptySet(),
new int[] {2},
operatorContext.getBySuffix("Is"))));
branches.add(
Collections.singletonList(
new ImmutableParameter(
"age",
Collections.emptySet(),
new int[] {3},
operatorContext.getBySuffix("GreaterThan"))));
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod(
"findByFirstNameAndLastNameOrAddressCityOrAgeGreaterThan",
String.class,
String.class,
String.class,
Integer.class),
new Object[] {"Milad", "Naseri", "Tabriz", 100}));
assertThat(selected, is(notNullValue()));
assertThat(selected, hasSize(2));
assertThat(selected.get(0).getId(), isIn(Arrays.asList("k1", "k3")));
assertThat(selected.get(1).getId(), isIn(Arrays.asList("k1", "k3")));
}
@Test
public void testSorting() throws Exception {
final ImmutableOrder first =
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT);
final ImmutableOrder second =
new ImmutableOrder(SortDirection.ASCENDING, "lastName", NullHandling.DEFAULT);
final ImmutableSort sort = new ImmutableSort(Arrays.asList(first, second));
final WrappedSortParameterExtractor sortExtractor = new WrappedSortParameterExtractor(sort);
final List<List<Parameter>> branches = new ArrayList<>();
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, sortExtractor, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {}));
assertThat(selected, hasSize(4));
assertThat(selected, containsInAnyOrder(dataStore.retrieveAll().toArray()));
assertThat(selected.get(0).getId(), is("k4"));
assertThat(selected.get(1).getId(), is("k3"));
assertThat(selected.get(2).getId(), is("k2"));
assertThat(selected.get(3).getId(), is("k1"));
}
@Test
public void testPagingWhenPageStartIsBeyondSelection() throws Exception {
final List<List<Parameter>> branches = new ArrayList<>();
final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0);
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, branches, null, null);
final SelectDataStoreOperation<String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll", Pageable.class),
new Object[] {PageRequest.of(2, 10)}));
assertThat(selected, is(empty()));
}
@Test
public void testPagingWhenLastPageIsNotFull() throws Exception {
final PageParameterExtractor pageExtractor = new PageablePageParameterExtractor(0);
final List<List<Parameter>> branches = Collections.emptyList();
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, pageExtractor, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll", Pageable.class),
new Object[] {PageRequest.of(1, 3)}));
assertThat(selected, hasSize(1));
}
@Test
public void testLimitingTheResult() throws Exception {
for (int limit = 1; limit < 10; limit++) {
final List<List<Parameter>> branches = Collections.emptyList();
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, limit, null, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {}));
assertThat(selected, hasSize(Math.min(limit, dataStore.retrieveAll().size())));
}
}
@Test
public void testLoadingDistinctValues() throws Exception {
dataStore.save("k5", new Person().setId("k1"));
final List<List<Parameter>> branches = Collections.emptyList();
// not distinct
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
final List<Person> selected =
operation.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {}));
assertThat(selected, hasSize(5));
// distinct
final DefaultQueryDescriptor descriptorDistinct =
new DefaultQueryDescriptor(true, null, 0, null, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operationDistinct =
new SelectDataStoreOperation<>(descriptorDistinct);
final List<Person> selectedDistinct =
operationDistinct.execute(
dataStore,
null,
new ImmutableInvocation(
RepositoryWithValidMethods.class.getMethod("findAll"), new Object[] {}));
assertThat(selectedDistinct, hasSize(4));
}
@Test
public void testToString() {
final List<List<Parameter>> branches = Collections.emptyList();
final DefaultQueryDescriptor descriptor =
new DefaultQueryDescriptor(false, null, 0, null, null, branches, null, null);
final DataStoreOperation<List<Person>, String, Person> operation =
new SelectDataStoreOperation<>(descriptor);
assertThat(operation.toString(), is(descriptor.toString()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomIntegerKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.RandomIntegerKeyGenerator;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public class RandomIntegerKeyGeneratorTest extends BaseKeyGeneratorTest<Integer> {
@Override
protected KeyGenerator<Integer> getKeyGenerator() {
return new RandomIntegerKeyGenerator();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AssignableRepositoryMetadataResolverTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.MalformedRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class AssignableRepositoryMetadataResolverTest {
@Test(expectedExceptions = RepositoryDefinitionException.class,
expectedExceptionsMessageRegExp = ".*?: Expected interface to extend .*?\\.Repository")
public void testResolvingFromNonInheritingRepository() {
new AssignableRepositoryMetadataResolver().resolve(MalformedRepository.class);
}
@Test
public void testResolvingFromInheritingRepository() {
final RepositoryMetadata metadata = new AssignableRepositoryMetadataResolver().resolve(
SimplePersonRepository.class);
assertThat(metadata, is(notNullValue()));
assertThat(metadata.getRepositoryInterface(), equalTo((Class) SimplePersonRepository.class));
assertThat(metadata.getEntityType(), equalTo((Class) Person.class));
assertThat(metadata.getIdentifierType(), equalTo((Class) String.class));
assertThat(metadata.getIdentifierProperty(), is("id"));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialIntegerKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialIntegerKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.SequentialIntegerKeyGenerator;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public class SequentialIntegerKeyGeneratorTest extends BaseKeyGeneratorTest<Integer> {
@Override
protected KeyGenerator<Integer> getKeyGenerator() {
return new SequentialIntegerKeyGenerator();
}
@Test
public void testKeysBeingSequential() {
final KeyGenerator<Integer> keyGenerator = getKeyGenerator();
Integer last = 0;
for (int i = 0; i < 100; i++) {
final Integer key = keyGenerator.generate();
assertThat(key, is(last + 1));
last = key;
}
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/UUIDKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.UUIDKeyGenerator;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public class UUIDKeyGeneratorTest extends BaseKeyGeneratorTest<String> {
@Override
protected KeyGenerator<String> getKeyGenerator() {
return new UUIDKeyGenerator();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRepositoryMetadataResolverTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.sample.mocks.NullReturningRepositoryMetadataResolver;
import com.mmnaseri.utils.spring.data.sample.models.EmptyEntity;
import org.springframework.data.repository.Repository;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class AbstractRepositoryMetadataResolverTest {
@Test(expectedExceptions = RepositoryDefinitionException.class,
expectedExceptionsMessageRegExp = ".*?: Repository interface must not be null")
public void testThatItDoesNotAcceptNull() {
new NullReturningRepositoryMetadataResolver().resolve(null);
}
@Test(expectedExceptions = RepositoryDefinitionException.class,
expectedExceptionsMessageRegExp = ".*?: Cannot resolve repository metadata for a class object that isn't an"
+ " interface")
public void testThatItOnlyAcceptsInterfaces() {
new NullReturningRepositoryMetadataResolver().resolve(EmptyEntity.class);
}
@Test(expectedExceptions = RepositoryDefinitionException.class,
expectedExceptionsMessageRegExp = ".*?: Repository interface needs to be declared as public")
public void testThatItOnlyAcceptsPublicInterfaces() {
new NullReturningRepositoryMetadataResolver().resolve(SamplePrivateInterface.class);
}
@Test
public void testThatItPassesAPublicInterfaceToTheSubClass() {
final NullReturningRepositoryMetadataResolver resolver = new NullReturningRepositoryMetadataResolver();
resolver.resolve(Repository.class);
assertThat(resolver.getRepositoryInterface(), equalTo((Class) Repository.class));
}
private interface SamplePrivateInterface {
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperationTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/MethodInvocationDataStoreOperationTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.error.DataOperationExecutionException;
import com.mmnaseri.utils.spring.data.sample.usecases.domain.MappedClass;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class MethodInvocationDataStoreOperationTest {
@Test(expectedExceptions = DataOperationExecutionException.class)
public void testAccessingPrivateMethod() throws Exception {
final MethodInvocationDataStoreOperation<Object, Object> operation = new MethodInvocationDataStoreOperation<>(
new MappedClass(null), MappedClass.class.getDeclaredMethod("privateMethod"));
operation.execute(null, null, new ImmutableInvocation(null, new Object[]{}));
}
@Test(expectedExceptions = DataOperationExecutionException.class)
public void testAccessingErrorThrowingMethod() throws Exception {
final MethodInvocationDataStoreOperation<Object, Object> operation = new MethodInvocationDataStoreOperation<>(
new MappedClass(null), MappedClass.class.getDeclaredMethod("errorThrowingMethod"));
operation.execute(null, null, new ImmutableInvocation(null, new Object[]{}));
}
@Test
public void testCallingNormalMethod() throws Exception {
final Object value = new Object();
final MethodInvocationDataStoreOperation<Object, Object> operation = new MethodInvocationDataStoreOperation<>(
new MappedClass(value), MappedClass.class.getDeclaredMethod("validMethod"));
final Object result = operation.execute(null, null, new ImmutableInvocation(null, new Object[]{}));
assertThat(result, is(value));
}
@Test
public void testToString() throws Exception {
final Method method = MappedClass.class.getDeclaredMethod("errorThrowingMethod");
final MappedClass instance = new MappedClass(null);
final MethodInvocationDataStoreOperation<Object, Object> operation = new MethodInvocationDataStoreOperation<>(
instance, method);
assertThat(operation.toString(), is(method + " on " + instance));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableMatchedOperatorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.MatchedOperator;
import com.mmnaseri.utils.spring.data.domain.Operator;
import com.mmnaseri.utils.spring.data.domain.impl.matchers.IsFalseMatcher;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.Random;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/17/16, 12:41 PM)
*/
public class ImmutableMatchedOperatorTest {
private Operator original;
private MatchedOperator matchedOperator;
@BeforeMethod
public void setUp() {
original =
new ImmutableOperator(
"operator", new Random().nextInt(), new IsFalseMatcher(), "a", "b", "c");
matchedOperator = new ImmutableMatchedOperator(original, "a");
}
@Test
public void testDelegation() {
assertThat(matchedOperator.getMatcher(), is(original.getMatcher()));
assertThat(matchedOperator.getName(), is(original.getName()));
assertThat(matchedOperator.getOperands(), is(original.getOperands()));
assertThat(matchedOperator.getTokens(), is(original.getTokens()));
}
@Test
public void testMatchedToken() {
assertThat(matchedOperator.getMatchedToken(), is("a"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultRepositoryMetadataResolverTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.AnnotatedInheritingRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.SampleAnnotatedRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.SimplePersonRepository;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultRepositoryMetadataResolverTest {
@Test
public void testThatItResolvesUsingAnnotations() {
final RepositoryMetadata metadata = new DefaultRepositoryMetadataResolver().resolveFromInterface(
SampleAnnotatedRepository.class);
assertThat(metadata, is(notNullValue()));
}
@Test
public void testThatItResolvesUsingInheritance() {
final RepositoryMetadata metadata = new DefaultRepositoryMetadataResolver().resolveFromInterface(
SimplePersonRepository.class);
assertThat(metadata, is(notNullValue()));
}
@Test
public void testThatAnnotationTakesPrecedenceOverInheritance() {
final RepositoryMetadata metadata = new DefaultRepositoryMetadataResolver().resolveFromInterface(
AnnotatedInheritingRepository.class);
assertThat(metadata, is(notNullValue()));
assertThat(metadata.getEntityType(), is(Matchers.equalTo(Person.class)));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AbstractRandomKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.sample.mocks.DuplicatingKeyGenerator;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/12/16, 3:28 PM)
*/
public class AbstractRandomKeyGeneratorTest {
@Test
public void testThatGeneratorProtectsUsFromDuplicates() {
final Set<Integer> generatedKeys = new HashSet<>();
final KeyGenerator<Integer> generator = new DuplicatingKeyGenerator();
for (int i = 0; i < 1000; i++) {
final Integer key = generator.generate();
assertThat(generatedKeys, not(hasItem(key)));
generatedKeys.add(key);
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/PropertyComparatorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.query.NullHandling;
import com.mmnaseri.utils.spring.data.query.SortDirection;
import com.mmnaseri.utils.spring.data.query.impl.ImmutableOrder;
import com.mmnaseri.utils.spring.data.sample.models.Address;
import com.mmnaseri.utils.spring.data.sample.models.ChildZip;
import com.mmnaseri.utils.spring.data.sample.models.OtherChildZip;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.models.Zip;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/11/16)
*/
public class PropertyComparatorTest {
@Test(expectedExceptions = InvalidArgumentException.class)
public void testWhenFirstValueDoesNotExist() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT));
//noinspection ResultOfMethodCallIgnored
comparator.compare(new Address(), new Person());
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testWhenSecondValueDoesNotExist() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.DEFAULT));
//noinspection ResultOfMethodCallIgnored
comparator.compare(new Person(), new Address());
}
@Test
public void testNullFirst() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_FIRST));
assertThat(
comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()),
is(1));
assertThat(
comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))),
is(-1));
}
@Test
public void testNullLast() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST));
assertThat(
comparator.compare(new Person().setAddress(new Address().setCity("A")), new Person()),
is(-1));
assertThat(
comparator.compare(new Person(), new Person().setAddress(new Address().setCity("A"))),
is(1));
}
@Test
public void testBothAreNull() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address.city", NullHandling.NULLS_LAST));
assertThat(comparator.compare(new Person(), new Person()), is(0));
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testWhenValuesAreNotComparable() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "address", NullHandling.NULLS_LAST));
//noinspection ResultOfMethodCallIgnored
comparator.compare(
new Person().setAddress(new Address()), new Person().setAddress(new Address()));
}
@Test
public void testWhenSecondIsSubTypeOfFirst() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST));
final int comparison =
comparator.compare(
new Person().setAddressZip(new Zip().setPrefix("a")),
new Person().setAddressZip(new ChildZip().setPrefix("b")));
assertThat(comparison, is(-1));
}
@Test
public void testWhenFirstIsSubTypeOfSecond() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST));
final int comparison =
comparator.compare(
new Person().setAddressZip(new ChildZip().setPrefix("b")),
new Person().setAddressZip(new Zip().setPrefix("a")));
assertThat(comparison, is(1));
}
@Test(expectedExceptions = InvalidArgumentException.class)
public void testWhenValuesAreNotOfTheSameType() {
final PropertyComparator comparator =
new PropertyComparator(
new ImmutableOrder(SortDirection.ASCENDING, "addressZip", NullHandling.NULLS_FIRST));
//noinspection ResultOfMethodCallIgnored
comparator.compare(
new Person().setAddressZip(new ChildZip().setPrefix("b")),
new Person().setAddressZip(new OtherChildZip().setPrefix("a")));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/SequentialLongKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.SequentialLongKeyGenerator;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public class SequentialLongKeyGeneratorTest extends BaseKeyGeneratorTest<Long> {
@Override
protected KeyGenerator<Long> getKeyGenerator() {
return new SequentialLongKeyGenerator();
}
@Test
public void testKeysBeingSequential() {
final KeyGenerator<Long> keyGenerator = getKeyGenerator();
Long last = 0L;
for (int i = 0; i < 100; i++) {
final Long key = keyGenerator.generate();
assertThat(key, is(last + 1));
last = key;
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperationTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DescribedDataStoreOperationTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.proxy.RepositoryConfiguration;
import com.mmnaseri.utils.spring.data.query.DataFunction;
import com.mmnaseri.utils.spring.data.query.QueryDescriptor;
import com.mmnaseri.utils.spring.data.query.impl.DefaultDataFunctionRegistry;
import com.mmnaseri.utils.spring.data.query.impl.DefaultQueryDescriptor;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingDataFunction;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingSelectDataStoreOperation;
import com.mmnaseri.utils.spring.data.store.DataStore;
import com.mmnaseri.utils.spring.data.store.impl.MemoryDataStore;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DescribedDataStoreOperationTest {
@Test
public void testExecutionWithoutAnyFunctions() {
final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, null, 0, null, null, null, null,
null);
final List<Object> selection = new ArrayList<>();
final SpyingSelectDataStoreOperation<Object, Object> operationSpy = new SpyingSelectDataStoreOperation<>(
descriptor, selection);
final DescribedDataStoreOperation<Object, Object> operation = new DescribedDataStoreOperation<>(operationSpy,
null);
assertThat(operationSpy.isCalled(), is(false));
final Object result = operation.execute(new MemoryDataStore<>(Object.class), null, null);
assertThat(operationSpy.isCalled(), is(true));
assertThat(result, Matchers.is(selection));
}
@Test
public void testExecutionWithCustomFunction() {
final DefaultQueryDescriptor descriptor = new DefaultQueryDescriptor(false, "xyz", 0, null, null, null, null,
null);
final List<Object> selection = new ArrayList<>();
final Object transformed = new Object();
final DefaultDataFunctionRegistry functionRegistry = new DefaultDataFunctionRegistry();
final SpyingDataFunction<Object> spy = new SpyingDataFunction<>(new DataFunction<Object>() {
@Override
public <K, E> Object apply(DataStore<K, E> dataStore, QueryDescriptor query,
RepositoryConfiguration configuration, List<E> current) {
return transformed;
}
});
functionRegistry.register("xyz", spy);
final SpyingSelectDataStoreOperation<Object, Object> operationSpy = new SpyingSelectDataStoreOperation<>(
descriptor, selection);
final DescribedDataStoreOperation<Object, Object> operation = new DescribedDataStoreOperation<>(operationSpy,
functionRegistry);
assertThat(operationSpy.isCalled(), is(false));
final Object result = operation.execute(new MemoryDataStore<>(Object.class), null, null);
assertThat(operationSpy.isCalled(), is(true));
assertThat(result, is(transformed));
assertThat(spy.getInvocations(), hasSize(1));
assertThat(spy.getInvocations().get(0).getSelection(), Matchers.<Object>is(selection));
}
@Test
public void testToString() {
final SelectDataStoreOperation<Object, Object> selectOperation = new SelectDataStoreOperation<>(
new DefaultQueryDescriptor(false, null, 0, null, null, null, null, null));
final DescribedDataStoreOperation<Object, Object> describedOperation = new DescribedDataStoreOperation<>(
selectOperation, null);
assertThat(describedOperation.toString(), is(selectOperation.toString()));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/RandomLongKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import com.mmnaseri.utils.spring.data.domain.impl.key.RandomLongKeyGenerator;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public class RandomLongKeyGeneratorTest extends BaseKeyGeneratorTest<Long> {
@Override
protected KeyGenerator<Long> getKeyGenerator() {
return new RandomLongKeyGenerator();
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/MethodQueryDescriptionExtractorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.Modifier;
import com.mmnaseri.utils.spring.data.domain.Parameter;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.QueryParserException;
import com.mmnaseri.utils.spring.data.proxy.RepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.proxy.impl.DefaultRepositoryFactoryConfiguration;
import com.mmnaseri.utils.spring.data.query.*;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.MalformedRepository;
import com.mmnaseri.utils.spring.data.sample.repositories.RepositoryWithValidMethods;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.List;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/21/15)
*/
public class MethodQueryDescriptionExtractorTest {
private QueryDescriptionExtractor<Method> extractor;
private RepositoryMetadata malformedRepositoryMetadata;
private RepositoryMetadata sampleRepositoryMetadata;
private RepositoryFactoryConfiguration configuration;
@BeforeMethod
public void setUp() {
extractor = new MethodQueryDescriptionExtractor(new DefaultOperatorContext());
malformedRepositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class,
MalformedRepository.class, "id");
sampleRepositoryMetadata = new ImmutableRepositoryMetadata(String.class, Person.class,
RepositoryWithValidMethods.class, "id");
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Malformed query method name.*")
public void testMethodNameNotStartingWithNormalWord() throws Exception {
configuration = new DefaultRepositoryFactoryConfiguration();
extractor.extract(malformedRepositoryMetadata, configuration, MalformedRepository.class.getMethod("Malformed"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: There is already a limit of 5 specified for this query:.*")
public void testMultipleLimitsUsingFirst() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findFirst5First10"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: There is already a limit of 1 specified for this query:.*")
public void testMultipleLimitsUsingFirstOne() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findFirstFirst10"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: There is already a limit of 10 specified for this query:.*")
public void testMultipleLimits() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findTop10Top5"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: You have already stated that this query should return distinct "
+ "items:.*")
public void testMultipleDistinctFlags() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findDistinctDistinct"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Query method name cannot end with `By`")
public void testNonSimpleQueryEndingInBy() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findTop10DistinctBy"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Could not find property `unknownProperty`.*")
public void testUnknownPropertyInExpression() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByUnknownProperty"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Expected to see parameter with index 0")
public void testTooFewParameterNumber() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstName"));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Expected more tokens to follow AND/OR operator")
public void testTooFewExpressionEndingInOr() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstNameOr", String.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Expected more tokens to follow AND/OR operator")
public void testTooFewExpressionEndingInAnd() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstNameOr", String.class));
}
@Test(expectedExceptions = QueryParserException.class, expectedExceptionsMessageRegExp = ".*: Invalid parameter types for operator IS on property firstName: \\[class java\\.lang\\.Object]")
public void testBadParameterType() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstName", Object.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Invalid last argument: expected paging or sorting.*?")
public void testBadLastParameter() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstName", String.class, Object.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Too many parameters.*?")
public void testTooManyParameters() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration, MalformedRepository.class
.getMethod("findByFirstName", String.class, Object.class, Object.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Could not find property `firstNameOrderBy` on `class com.mmnaseri"
+ ".utils.spring.data.sample.models.Person`")
public void testWithTrailingOrderBy() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstNameOrderBy", String.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Failed to get a property descriptor for expression: Xyz")
public void testWithOrderByInvalidProperty() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstNameOrderByXyzDesc", String.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: You cannot specify both an order-by clause and a dynamic ordering")
public void testWithMultipleOrders() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration, MalformedRepository.class
.getMethod("findByFirstNameOrderByFirstNameAsc", String.class,
org.springframework.data.domain.Sort.class));
}
@Test(expectedExceptions = QueryParserException.class,
expectedExceptionsMessageRegExp = ".*?: Sort property `address` is not comparable in "
+ "`findByFirstNameOrderByAddressAsc`")
public void testWithOrderByNonComparableProperty() throws Exception {
extractor.extract(malformedRepositoryMetadata, configuration,
MalformedRepository.class.getMethod("findByFirstNameOrderByAddressAsc", String.class));
}
@Test
public void testIntegrity() {
assertThat(((MethodQueryDescriptionExtractor) extractor).getOperatorContext(), is(notNullValue()));
}
@Test
public void testReadMethodWithoutAnyCriteria() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class.getMethod("find"));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getConfiguration(), is(configuration));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
assertThat(descriptor.getRepositoryMetadata(), is(sampleRepositoryMetadata));
assertThat(descriptor.getBranches(), is(empty()));
}
@Test
public void testCustomFunctionWithoutAnyCriteria() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class.getMethod("test"));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getConfiguration(), is(configuration));
assertThat(descriptor.getFunction(), is("test"));
assertThat(descriptor.getLimit(), is(0));
assertThat(descriptor.getRepositoryMetadata(), is(sampleRepositoryMetadata));
assertThat(descriptor.getBranches(), is(empty()));
}
@Test
public void testQueryMethodWithSingleBranch() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstNameAndLastNameEquals",
String.class, String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getConfiguration(), is(configuration));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
assertThat(descriptor.getRepositoryMetadata(), is(sampleRepositoryMetadata));
assertThat(descriptor.getBranches(), hasSize(1));
final List<Parameter> parameters = descriptor.getBranches().get(0);
assertThat(parameters, hasSize(2));
assertThat(parameters.get(0).getIndices().length, is(1));
assertThat(parameters.get(0).getIndices()[0], is(0));
assertThat(parameters.get(0).getModifiers(), is(empty()));
assertThat(parameters.get(0).getPath(), is("firstName"));
assertThat(parameters.get(0).getOperator().getName(), is("IS"));
assertThat(parameters.get(1).getIndices().length, is(1));
assertThat(parameters.get(1).getIndices()[0], is(1));
assertThat(parameters.get(1).getModifiers(), is(empty()));
assertThat(parameters.get(1).getPath(), is("lastName"));
assertThat(parameters.get(1).getOperator().getName(), is("IS"));
}
@Test
public void testModifierOnSingleParameter() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstNameAndLastNameIgnoreCase",
String.class, String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getConfiguration(), is(configuration));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
assertThat(descriptor.getRepositoryMetadata(), is(sampleRepositoryMetadata));
assertThat(descriptor.getBranches(), hasSize(1));
final List<Parameter> parameters = descriptor.getBranches().get(0);
assertThat(parameters, hasSize(2));
assertThat(parameters.get(0).getIndices().length, is(1));
assertThat(parameters.get(0).getIndices()[0], is(0));
assertThat(parameters.get(0).getModifiers(), is(empty()));
assertThat(parameters.get(0).getPath(), is("firstName"));
assertThat(parameters.get(0).getOperator().getName(), is("IS"));
assertThat(parameters.get(1).getIndices().length, is(1));
assertThat(parameters.get(1).getIndices()[0], is(1));
assertThat(parameters.get(1).getModifiers(), is(not(empty())));
assertThat(parameters.get(1).getModifiers(), contains(Modifier.IGNORE_CASE));
assertThat(parameters.get(1).getPath(), is("lastName"));
assertThat(parameters.get(1).getOperator().getName(), is("IS"));
}
@Test
public void testWithOrderBy() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class.getMethod(
"findByFirstNameOrderByLastNameDescAgeAsc",
String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
final Sort sort = descriptor.getSort(new ImmutableInvocation(null, new Object[0]));
assertThat(sort.getOrders(), hasSize(2));
assertThat(sort.getOrders().get(0).getDirection(), is(SortDirection.DESCENDING));
assertThat(sort.getOrders().get(0).getProperty(), is("lastName"));
assertThat(sort.getOrders().get(1).getDirection(), is(SortDirection.ASCENDING));
assertThat(sort.getOrders().get(1).getProperty(), is("age"));
}
@Test
public void testWithMultipleBranches() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstNameOrLastName",
String.class, String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(2));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getBranches().get(1), hasSize(1));
assertThat(descriptor.getBranches().get(1).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(1).get(0).getIndices()[0], is(1));
assertThat(descriptor.getBranches().get(1).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(1).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(1).get(0).getPath(), is("lastName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
}
@Test
public void testWithStaticSortingAndDynamicPaging() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstNameOrderByLastNameDesc",
String.class, Pageable.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
final List<Order> orders = descriptor.getSort(new ImmutableInvocation(null, null)).getOrders();
assertThat(orders, hasSize(1));
assertThat(orders.get(0).getProperty(), is("lastName"));
assertThat(orders.get(0).getDirection(), is(SortDirection.DESCENDING));
final Page page = descriptor.getPage(new ImmutableInvocation(null, new Object[]{null, PageRequest.of(0, 1)}));
assertThat(page, is(notNullValue()));
assertThat(page.getPageSize(), is(1));
assertThat(page.getPageNumber(), is(0));
}
@Test
public void testWithDynamicSortingAndDynamicPaging() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstName", String.class,
Pageable.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
final ImmutableInvocation invocation = new ImmutableInvocation(null, new Object[]{null, PageRequest.of(0, 1,
org.springframework.data.domain.Sort
.by(org.springframework.data.domain.Sort.Direction.ASC,
"firstName",
"lastName"))});
final List<Order> orders = descriptor.getSort(invocation).getOrders();
assertThat(orders, hasSize(2));
assertThat(orders.get(0).getProperty(), is("firstName"));
assertThat(orders.get(0).getDirection(), is(SortDirection.ASCENDING));
assertThat(orders.get(1).getProperty(), is("lastName"));
assertThat(orders.get(1).getDirection(), is(SortDirection.ASCENDING));
final Page page = descriptor.getPage(invocation);
assertThat(page, is(notNullValue()));
assertThat(page.getPageSize(), is(1));
assertThat(page.getPageNumber(), is(0));
}
@Test
public void testWithDynamicSortAndNoPaging() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("findByFirstName", String.class,
org.springframework.data.domain.Sort.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
final ImmutableInvocation invocation = new ImmutableInvocation(null, new Object[]{null,
org.springframework.data.domain.Sort.by(
org.springframework.data.domain.Sort.Direction.ASC,
"firstName",
"lastName")});
final List<Order> orders = descriptor.getSort(invocation).getOrders();
assertThat(orders, hasSize(2));
assertThat(orders.get(0).getProperty(), is("firstName"));
assertThat(orders.get(0).getDirection(), is(SortDirection.ASCENDING));
assertThat(orders.get(1).getProperty(), is("lastName"));
assertThat(orders.get(1).getDirection(), is(SortDirection.ASCENDING));
final Page page = descriptor.getPage(invocation);
assertThat(page, is(nullValue()));
}
@Test
public void testAllIgnoreCase() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class.getMethod(
"findByFirstNameAndLastNameAllIgnoreCase",
String.class, String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(2));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), contains(Modifier.IGNORE_CASE));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
assertThat(descriptor.getBranches().get(0).get(1).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(1).getIndices()[0], is(1));
assertThat(descriptor.getBranches().get(0).get(1).getModifiers(), contains(Modifier.IGNORE_CASE));
assertThat(descriptor.getBranches().get(0).get(1).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(1).getPath(), is("lastName"));
assertThat(descriptor.getFunction(), is(nullValue()));
assertThat(descriptor.getLimit(), is(0));
}
@Test
public void testFunction() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class
.getMethod("functionNameByFirstName",
String.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices()[0], is(0));
assertThat(descriptor.getBranches().get(0).get(0).getModifiers(), is(empty()));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IS"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
//because we are only looking at the first "word".
assertThat(descriptor.getFunction(), is("function"));
assertThat(descriptor.getLimit(), is(0));
}
@Test
public void testInOperator() throws Exception {
final QueryDescriptor descriptor = extractor.extract(sampleRepositoryMetadata, configuration,
RepositoryWithValidMethods.class.getMethod("findByFirstNameIn", Collection.class));
assertThat(descriptor, is(notNullValue()));
assertThat(descriptor.getBranches(), hasSize(1));
assertThat(descriptor.getBranches().get(0), hasSize(1));
assertThat(descriptor.getBranches().get(0).get(0).getIndices().length, is(1));
assertThat(descriptor.getBranches().get(0).get(0).getOperator().getName(), is("IN"));
assertThat(descriptor.getBranches().get(0).get(0).getPath(), is("firstName"));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/DefaultOperatorContextTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.error.DuplicateOperatorException;
import org.hamcrest.Matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class DefaultOperatorContextTest {
@Test
public void testRegistering() {
final DefaultOperatorContext context = new DefaultOperatorContext();
final ImmutableOperator operator = new ImmutableOperator("x", 1, null, "A");
context.register(operator);
assertThat(context.getBySuffix("A"), is(notNullValue()));
assertThat(context.getBySuffix("A"), Matchers.is(operator));
}
@Test(expectedExceptions = DuplicateOperatorException.class)
public void testRegisteringDuplicates() {
final DefaultOperatorContext context = new DefaultOperatorContext();
context.register(new ImmutableOperator("x", 1, null, "X", "A"));
context.register(new ImmutableOperator("y", 1, null, "B", "A"));
}
@Test
public void testLookingForNonExistentOperator() {
final DefaultOperatorContext context = new DefaultOperatorContext();
assertThat(context.getBySuffix("xyz"), is(nullValue()));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolverTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/AnnotationRepositoryMetadataResolverTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.RepositoryMetadata;
import com.mmnaseri.utils.spring.data.error.RepositoryDefinitionException;
import com.mmnaseri.utils.spring.data.sample.models.Person;
import com.mmnaseri.utils.spring.data.sample.repositories.SampleAnnotatedRepository;
import org.springframework.data.repository.Repository;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class AnnotationRepositoryMetadataResolverTest {
@Test(expectedExceptions = RepositoryDefinitionException.class,
expectedExceptionsMessageRegExp = ".*?: Expected the repository to be annotated with @RepositoryDefinition")
public void testResolvingFromRepositoryWithoutAnnotations() {
new AnnotationRepositoryMetadataResolver().resolve(Repository.class);
}
@Test
public void testResolvingFromAnnotatedRepository() {
final RepositoryMetadata metadata = new AnnotationRepositoryMetadataResolver().resolve(
SampleAnnotatedRepository.class);
assertThat(metadata, is(notNullValue()));
assertThat(metadata.getRepositoryInterface(), equalTo((Class) SampleAnnotatedRepository.class));
assertThat(metadata.getEntityType(), equalTo((Class) Person.class));
assertThat(metadata.getIdentifierType(), equalTo((Class) String.class));
assertThat(metadata.getIdentifierProperty(), is("id"));
}
} | java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/BaseKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (10/8/15)
*/
public abstract class BaseKeyGeneratorTest<S> {
protected abstract KeyGenerator<S> getKeyGenerator();
@Test(invocationCount = 100)
public void testThatKeysAreUnique() {
final KeyGenerator<S> keyGenerator = getKeyGenerator();
final Set<S> keys = new HashSet<>();
for (int i = 0; i < 200; i++) {
final S key = keyGenerator.generate();
assertThat(keys.contains(key), is(false));
keys.add(key);
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/ImmutableParameterTest.java | package com.mmnaseri.utils.spring.data.domain.impl;
import org.testng.annotations.Test;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class ImmutableParameterTest {
@Test
public void testToString() {
final ImmutableParameter parameter =
new ImmutableParameter(
"x.y.z",
Collections.emptySet(),
new int[] {2, 3, 4},
new ImmutableOperator("op", 0, null));
assertThat(parameter.toString(), is("(x.y.z,op,[2, 3, 4],[])"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/BsonObjectIdKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl.key;
import org.bson.types.ObjectId;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import java.util.HashSet;
import java.util.Set;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.notNullValue;
public class BsonObjectIdKeyGeneratorTest {
private BsonObjectIdKeyGenerator generator;
@BeforeMethod
public void setUp() {
generator = new BsonObjectIdKeyGenerator();
}
@Test
public void testNotNullValue() {
assertThat(generator.generate(), is(notNullValue()));
}
@Test
public void testUniqueness() {
final Set<ObjectId> set = new HashSet<>();
for (int i = 0; i < 1000; i++) {
final ObjectId id = generator.generate();
assertThat(set, not(contains(id)));
}
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialIntegerKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl.key;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (6/14/16, 12:25 PM)
*/
public class ConfigurableSequentialIntegerKeyGeneratorTest {
@Test
public void testKeyGenerationWithDefaultSettings() {
final KeyGenerator<Integer> generator = new ConfigurableSequentialIntegerKeyGenerator();
assertThat(generator.generate(), is(1));
assertThat(generator.generate(), is(2));
assertThat(generator.generate(), is(3));
}
@Test
public void testKeyGenerationWithDefaultStepAndCustomInitialValue() {
final int initialValue = 100;
final KeyGenerator<Integer> generator =
new ConfigurableSequentialIntegerKeyGenerator(initialValue);
assertThat(generator.generate(), is(initialValue));
assertThat(generator.generate(), is(initialValue + 1));
assertThat(generator.generate(), is(initialValue + 2));
}
@Test
public void testKeyGenerationWithCustomStepAndCustomInitialValue() {
final int initialValue = 100;
final int step = 3;
final KeyGenerator<Integer> generator =
new ConfigurableSequentialIntegerKeyGenerator(initialValue, step);
assertThat(generator.generate(), is(initialValue));
assertThat(generator.generate(), is(initialValue + step));
assertThat(generator.generate(), is(initialValue + step * 2));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/key/ConfigurableSequentialLongKeyGeneratorTest.java | package com.mmnaseri.utils.spring.data.domain.impl.key;
import com.mmnaseri.utils.spring.data.domain.KeyGenerator;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (6/14/16, 12:27 PM)
*/
public class ConfigurableSequentialLongKeyGeneratorTest {
@Test
public void testKeyGenerationWithDefaultSettings() {
final KeyGenerator<Long> generator = new ConfigurableSequentialLongKeyGenerator();
assertThat(generator.generate(), is(1L));
assertThat(generator.generate(), is(2L));
assertThat(generator.generate(), is(3L));
}
@Test
public void testKeyGenerationWithDefaultStepAndCustomInitialValue() {
final long initialValue = 100L;
final KeyGenerator<Long> generator = new ConfigurableSequentialLongKeyGenerator(initialValue);
assertThat(generator.generate(), is(initialValue));
assertThat(generator.generate(), is(initialValue + 1));
assertThat(generator.generate(), is(initialValue + 2));
}
@Test
public void testKeyGenerationWithCustomStepAndCustomInitialValue() {
final long initialValue = 100L;
final long step = 3L;
final KeyGenerator<Long> generator =
new ConfigurableSequentialLongKeyGenerator(initialValue, step);
assertThat(generator.generate(), is(initialValue));
assertThat(generator.generate(), is(initialValue + step));
assertThat(generator.generate(), is(initialValue + step * 2));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/RegexMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class RegexMatcherTest {
@Test
public void testWhenActualIsNull() {
assertThat(new RegexMatcher().matches(null, ""), is(false));
}
@Test
public void testWhenPatternIsNull() {
assertThat(new RegexMatcher().matches("", null), is(false));
}
@Test
public void testWhenItemMatchesPatternPartially() {
assertThat(new RegexMatcher().matches("hello", "lo"), is(false));
}
@Test
public void testWhenItemDoesNotMatchPatternInAnyWay() {
assertThat(new RegexMatcher().matches("hello", "\\d+"), is(false));
}
@Test
public void testWhenItemMatchesPattern() {
assertThat(new RegexMatcher().matches("12345", "\\d+"), is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleComparableMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableParameter;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.sample.mocks.NotMatchingSimpleComparableMatcher;
import org.testng.annotations.Test;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class AbstractSimpleComparableMatcherTest {
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = ".*x.y.z.*")
public void testWhenActualIsNotComparable() {
final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), new Object(), 2);
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = ".*x.y.z.*")
public void testWhenPivotIsNotComparable() {
final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, new Object());
}
@Test
public void testWhenBothAreComparable() {
final NotMatchingSimpleComparableMatcher matcher = new NotMatchingSimpleComparableMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, 2);
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotLikeMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class IsNotLikeMatcherTest {
@Test
public void testWhenBothSubjectAndReferenceAreNull() {
assertThat(new IsNotLikeMatcher().matches(null, null), is(false));
}
@Test
public void testWhenSubjectIsNullAndReferenceIsNotNull() {
assertThat(new IsNotLikeMatcher().matches(null, ""), is(true));
}
@Test
public void testWhenReferenceIsNullAndSubjectIsNotNull() {
assertThat(new IsNotLikeMatcher().matches("", null), is(true));
}
@Test
public void testWhenTheyAreNotAlike() {
assertThat(new IsNotLikeMatcher().matches("Hello World", "World"), is(true));
}
@Test
public void testWhenTheyAreAlike() {
assertThat(new IsNotLikeMatcher().matches("Hello world!", "hello WORLD!"), is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotInMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class IsNotInMatcherTest {
@Test
public void testWhenItemIsNull() {
assertThat(new IsNotInMatcher().matches(null, Collections.emptyList()), is(true));
}
@Test
public void testWhenItemIsInCollection() {
assertThat(new IsNotInMatcher().matches(1, Arrays.asList(1, 2, 3, 4)), is(false));
}
@Test
public void testWhenItemIsNotInCollection() {
assertThat(new IsNotInMatcher().matches(1, Arrays.asList(3, 4, 5, 6)), is(true));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/IsNotBetweenMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import org.testng.annotations.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/29/15)
*/
public class IsNotBetweenMatcherTest {
@Test
public void testWhenActualIsNull() {
assertThat(new IsNotBetweenMatcher().matches(null, 1, 2), is(true));
}
@Test
public void testWhenLowerBoundIsNull() {
assertThat(new IsNotBetweenMatcher().matches(1, null, 2), is(false));
}
@Test
public void testWhenUpperBoundIsNull() {
assertThat(new IsNotBetweenMatcher().matches(1, 2, null), is(false));
}
@Test
public void testWhenValueIsBelowRange() {
assertThat(new IsNotBetweenMatcher().matches(1, 3, 6), is(true));
}
@Test
public void testWhenValueIsAboveRange() {
assertThat(new IsNotBetweenMatcher().matches(9, 3, 6), is(true));
}
@Test
public void testWhenRangeContainsValueInclusive() {
assertThat(new IsNotBetweenMatcher().matches(3, 3, 6), is(false));
assertThat(new IsNotBetweenMatcher().matches(6, 3, 6), is(false));
}
@Test
public void testWhenRangeContainsValueMidRange() {
assertThat(new IsNotBetweenMatcher().matches(4, 3, 6), is(false));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractCollectionMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableParameter;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.sample.mocks.SpyingCollectionMatcher;
import org.testng.annotations.Test;
import java.util.Arrays;
import java.util.HashSet;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (9/30/15)
*/
public class AbstractCollectionMatcherTest {
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = "Comparison property cannot be null: xyz")
public void testWhenPivotIsNull() {
new SpyingCollectionMatcher()
.matches(new ImmutableParameter("xyz", null, null, null), 1, new Object[] {null});
}
@Test
public void testPassingInAnArray() {
final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher();
matcher.matches(null, null, new Object[] {new Object[] {1, 2, 3, 4}});
assertThat(matcher.getCollection(), is(notNullValue()));
assertThat(matcher.getCollection(), hasSize(4));
assertThat(matcher.getCollection(), contains(1, 2, 3, 4));
}
@Test
public void testPassingInAnIterator() {
final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher();
matcher.matches(null, null, new Object[] {Arrays.asList(1, 2, 3, 4).iterator()});
assertThat(matcher.getCollection(), is(notNullValue()));
assertThat(matcher.getCollection(), hasSize(4));
assertThat(matcher.getCollection(), contains(1, 2, 3, 4));
}
@Test
public void testPassingInAnIterable() {
final SpyingCollectionMatcher matcher = new SpyingCollectionMatcher();
matcher.matches(null, null, new Object[] {new HashSet<>(Arrays.asList(1, 2, 3, 4))});
assertThat(matcher.getCollection(), is(notNullValue()));
assertThat(matcher.getCollection(), hasSize(4));
assertThat(matcher.getCollection(), containsInAnyOrder(1, 2, 3, 4));
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = "Expected an array, an iterator, or an iterable object")
public void testPassingInAnythingElse() {
new SpyingCollectionMatcher().matches(null, null, new Object[] {new Object()});
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
mmnaseri/spring-data-mock | https://github.com/mmnaseri/spring-data-mock/blob/e8547729050c9454872a1038c23bb9b1288c8654/spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java | spring-data-mock/src/test/java/com/mmnaseri/utils/spring/data/domain/impl/matchers/AbstractSimpleStringMatcherTest.java | package com.mmnaseri.utils.spring.data.domain.impl.matchers;
import com.mmnaseri.utils.spring.data.domain.Modifier;
import com.mmnaseri.utils.spring.data.domain.impl.ImmutableParameter;
import com.mmnaseri.utils.spring.data.error.InvalidArgumentException;
import com.mmnaseri.utils.spring.data.sample.mocks.NotMatchingStringMatcher;
import org.testng.annotations.Test;
import java.util.Collections;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
/**
* @author Milad Naseri (m.m.naseri@gmail.com)
* @since 1.0 (4/10/16)
*/
public class AbstractSimpleStringMatcherTest {
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = ".*x.y.z.*")
public void testValueNotAString() {
final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), 1, "");
}
@Test(
expectedExceptions = InvalidArgumentException.class,
expectedExceptionsMessageRegExp = ".*x.y.z.*")
public void testParameterNotAString() {
final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", 1);
}
@Test
public void testWhenBothAreStrings() {
final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher();
matcher.matches(new ImmutableParameter("x.y.z", null, null, null), "", "");
}
@Test
public void testWhenIgnoringCase() {
final NotMatchingStringMatcher matcher = new NotMatchingStringMatcher();
matcher.matches(
new ImmutableParameter("x.y.z", Collections.singleton(Modifier.IGNORE_CASE), null, null),
"test",
"TEST");
assertThat(matcher.getActual(), is("test"));
assertThat(matcher.getArgument(), is("test"));
}
}
| java | MIT | e8547729050c9454872a1038c23bb9b1288c8654 | 2026-01-05T02:41:15.897176Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.