Move some unit tests from ebean-test back to ebean-core

This commit is contained in:
Rob Bygrave
2022-03-24 18:21:48 +13:00
parent f270c52c00
commit f58d6038c7
148 changed files with 339 additions and 383 deletions
@@ -0,0 +1,223 @@
package io.ebeaninternal.json;
import org.junit.jupiter.api.Test;
import java.io.*;
import java.util.*;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class ModifyAwareMapTest {
private ModifyAwareMap<String, String> createMap() {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
map.put("A", "one");
map.put("B", "two");
map.put("C", "three");
map.put("D", "four");
map.put("E", "five");
return new ModifyAwareMap<>(map);
}
private ModifyAwareMap<String, String> createEmptyMap() {
LinkedHashMap<String, String> map = new LinkedHashMap<>();
return new ModifyAwareMap<>(map);
}
@Test
public void testToString() {
ModifyAwareMap<String, String> map = createMap();
assertEquals(map.map.toString(), map.toString());
}
@Test
public void testIsMarkedDirty() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
map.put("A", "change");
assertTrue(map.isMarkedDirty());
}
@Test
public void testMarkAsModified() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
map.setMarkedDirty(true);
assertTrue(map.isMarkedDirty());
}
@Test
public void testSize() {
ModifyAwareMap<String, String> map = createMap();
assertEquals(5, map.size());
}
@Test
public void testIsEmpty() {
assertFalse(createMap().isEmpty());
assertTrue(createEmptyMap().isEmpty());
}
@Test
public void testContainsKey() {
ModifyAwareMap<String, String> map = createMap();
assertTrue(map.containsKey("A"));
assertFalse(map.containsKey("Z"));
}
@Test
public void testContainsValue() {
ModifyAwareMap<String, String> map = createMap();
assertTrue(map.containsValue("one"));
assertFalse(map.containsValue("junk"));
}
@Test
public void testGet() {
ModifyAwareMap<String, String> map = createMap();
assertEquals("two", map.get("B"));
assertNull(map.get("Z"));
assertFalse(map.isMarkedDirty());
}
@Test
public void testPut() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
map.put("A", "mod");
assertTrue(map.isMarkedDirty());
}
@Test
public void testRemove() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
map.remove("A");
assertTrue(map.isMarkedDirty());
}
@Test
public void testPutAllWithEmpty() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
Map<String, String> other = new HashMap<>();
map.putAll(other);
assertTrue(map.isMarkedDirty());
}
@Test
public void testPutAll() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
Map<String, String> other = new HashMap<>();
other.put("A", "one");
map.putAll(other);
assertTrue(map.isMarkedDirty());
}
@Test
public void testClear() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
map.clear();
assertTrue(map.isMarkedDirty());
}
@Test
public void testKeySet() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
Set<String> keys = map.keySet();
assertEquals(map.size(), keys.size());
assertTrue(keys.contains("A"));
assertFalse(map.isMarkedDirty());
}
@Test
public void testValues() {
ModifyAwareMap<String, String> map = createMap();
assertFalse(map.isMarkedDirty());
Collection<String> values = map.values();
assertEquals(map.size(), values.size());
assertTrue(values.contains("one"));
assertFalse(map.isMarkedDirty());
}
@Test
public void testEntrySet() {
ModifyAwareMap<String, String> map = createMap();
Set<Map.Entry<String, String>> entries = map.entrySet();
assertFalse(map.isMarkedDirty());
assertEquals(map.size(), entries.size());
assertFalse(map.isMarkedDirty());
}
@Test
public void serialise() throws IOException, ClassNotFoundException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
ModifyAwareMap<String, String> orig = createMap();
oos.writeObject(orig);
oos.flush();
oos.close();
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
ObjectInputStream ois = new ObjectInputStream(is);
@SuppressWarnings("unchecked")
ModifyAwareMap<String, String> read = (ModifyAwareMap<String, String>) ois.readObject();
assertThat(read).hasSize(orig.size());
}
@Test
public void equalsWhenEqual() {
ModifyAwareMap<String, String> mapA = createMap();
ModifyAwareMap<String, String> mapB = createMap();
assertThat(mapA).isEqualTo(mapB);
assertThat(mapA.hashCode()).isEqualTo(mapB.hashCode());
}
@Test
public void equalsWhenNotEqual() {
ModifyAwareMap<String, String> mapA = createMap();
ModifyAwareMap<String, String> mapB = createMap();
mapB.put("F", "Six");
assertThat(mapA).isNotEqualTo(mapB);
assertThat(mapA.hashCode()).isNotEqualTo(mapB.hashCode());
}
}
@@ -0,0 +1,137 @@
package io.ebeaninternal.server.cache;
import io.ebean.cache.ServerCacheFactory;
import io.ebean.cache.ServerCacheOptions;
import io.ebean.cache.ServerCacheType;
import io.ebean.config.DatabaseConfig;
import io.ebeaninternal.server.transaction.TableModState;
import org.junit.jupiter.api.Test;
import org.tests.model.basic.Contact;
import org.tests.model.basic.Customer;
import static org.assertj.core.api.Assertions.assertThat;
public class DefaultCacheHolderTest {
private final ThreadLocal<String> tenantId = new ThreadLocal<>();
private final ServerCacheFactory cacheFactory = new DefaultServerCacheFactory();
private final ServerCacheOptions defaultOptions = new ServerCacheOptions();
private CacheManagerOptions options() {
return new CacheManagerOptions(null, new DatabaseConfig(), true)
.with(defaultOptions, defaultOptions)
.with(cacheFactory, new TableModState());
}
@Test
public void getCache_normal() {
DefaultCacheHolder holder = new DefaultCacheHolder(options());
DefaultServerCache cache = cache(holder, Customer.class);
assertThat(cache.getName()).isEqualTo("org.tests.model.basic.Customer_B");
assertThat(cache.getShortName()).isEqualTo("Customer_B");
DefaultServerCache cache1 = cache(holder, Customer.class);
assertThat(cache1).isSameAs(cache);
DefaultServerCache cache2 = cache(holder, Contact.class);
assertThat(cache1).isNotSameAs(cache2);
assertThat(cache2.getName()).isEqualTo("org.tests.model.basic.Contact_B");
assertThat(cache2.getShortName()).isEqualTo("Contact_B");
}
private DefaultServerCache cache(DefaultCacheHolder holder, Class<?> type) {
return (DefaultServerCache) holder.getCache(type, ServerCacheType.BEAN);
}
@Test
public void getCache_multiTenant() throws Exception {
CacheManagerOptions builder = options().with(tenantId::get);
DefaultCacheHolder holder = new DefaultCacheHolder(builder);
tenantId.set("ten_1");
DefaultServerCache cache = cache(holder, Customer.class);
assertThat(cache.getName()).isEqualTo("org.tests.model.basic.Customer_B");
assertThat(cache.getShortName()).isEqualTo("Customer_B");
cache.put("1", "value-for-tenant1");
cache.put("2", "an other value-for-tenant1");
assertThat(cache.size()).isEqualTo(2);
tenantId.set("ten_2");
cache.put("1", "value-for-tenant2");
cache.put("2", "an other value-for-tenant2");
assertThat(cache.size()).isEqualTo(4);
assertThat(cache.get("1")).isEqualTo("value-for-tenant2");
assertThat(cache.get("2")).isEqualTo("an other value-for-tenant2");
tenantId.set("ten_1");
assertThat(cache.get("1")).isEqualTo("value-for-tenant1");
assertThat(cache.get("2")).isEqualTo("an other value-for-tenant1");
Exception[] exInThread = new Exception[1];
Thread t = new Thread(() -> {
try {
assertThat(cache.get("1")).isNull();
tenantId.set("ten_2");
cache.put("1", "value-for-tenant2");
cache.put("2", "an other value-for-tenant2");
tenantId.set(null);
cache.clear();
} catch (Exception e) {
exInThread[0] = e;
}
});
// do some async work
t.start();
t.join();
if (exInThread[0] != null) {
throw exInThread[0];
}
assertThat(cache.size()).isEqualTo(0);
}
@Test
public void clearAll() {
DefaultCacheHolder holder = new DefaultCacheHolder(options());
DefaultServerCache cache = cache(holder, Customer.class);
cache.put("foo", "foo");
assertThat(cache.size()).isEqualTo(1);
holder.clearAll();
assertThat(cache.size()).isEqualTo(0);
}
@Test
public void clearAll_multiTenant() {
CacheManagerOptions options = options().with(tenantId::get);
DefaultCacheHolder holder = new DefaultCacheHolder(options);
DefaultServerCache cache = cache(holder, Customer.class);
cache.put("foo", "foo");
assertThat(cache.size()).isEqualTo(1);
holder.clearAll();
assertThat(cache.size()).isEqualTo(0);
}
}
@@ -0,0 +1,52 @@
package io.ebeaninternal.server.cache;
import io.ebean.cache.ServerCacheConfig;
import io.ebean.cache.ServerCacheOptions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultServerCacheConfigTest {
private DefaultServerCacheConfig create(int maxSize, int maxIdleSecs, int maxSecsToLive, int trimFreq) {
ServerCacheOptions options = new ServerCacheOptions();
options.setMaxSize(maxSize);
options.setMaxIdleSecs(maxIdleSecs);
options.setMaxSecsToLive(maxSecsToLive);
options.setTrimFrequency(trimFreq);
return new DefaultServerCacheConfig(new ServerCacheConfig(null, null, null, options, null, null));
}
@Test
public void trimFreq_halfIdle() {
assertEquals(create(10000,10,20, 0).determineTrimFrequency(), 4);
}
@Test
public void trimFreq_halfIdle_withRounding() {
assertEquals(create(10000,11,20, 0).determineTrimFrequency(), 4);
}
@Test
public void trimFreq_halfTTL() {
assertEquals(create(10000,0,20, 0).determineTrimFrequency(), 9);
}
@Test
public void trimFreq_halfTTL_withRounding() {
assertEquals(create(10000,0,21, 0).determineTrimFrequency(), 9);
}
@Test
public void trimFreq_explicit() {
assertEquals(create(10000,10,20, 42).determineTrimFrequency(), 42);
}
}
@@ -0,0 +1,65 @@
package io.ebeaninternal.server.cache;
import io.ebean.cache.ServerCacheConfig;
import io.ebean.cache.ServerCacheOptions;
import io.ebean.cache.ServerCacheType;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DefaultServerCacheTest {
private DefaultServerCache createCache() {
ServerCacheOptions cacheOptions = new ServerCacheOptions();
cacheOptions.setMaxSize(100);
cacheOptions.setMaxIdleSecs(60);
cacheOptions.setMaxSecsToLive(600);
cacheOptions.setTrimFrequency(60);
ServerCacheConfig con = new ServerCacheConfig(ServerCacheType.BEAN, "foo", null, cacheOptions, null, null);
DefaultServerCacheConfig config = new DefaultServerCacheConfig(con);
return new DefaultServerCache(config);
}
@Test
public void testGetHitRatio() {
DefaultServerCache cache = createCache();
assertEquals(0, cache.hitRatio());
assertEquals(0, cache.getHitCount());
assertEquals(0, cache.getMissCount());
cache.put("A", "A");
cache.get("A");
assertEquals(100, cache.hitRatio());
assertEquals(1, cache.getHitCount());
assertEquals(0, cache.getMissCount());
cache.get("B");
assertEquals(50, cache.hitRatio());
assertEquals(1, cache.getMissCount());
cache.get("B");
cache.get("B");
assertEquals(25, cache.hitRatio());
assertEquals(3, cache.getMissCount());
assertEquals(1, cache.getHitCount());
}
@Test
public void testSize() {
DefaultServerCache cache = createCache();
assertEquals(0, cache.size());
cache.put("A", "A");
assertEquals(1, cache.size());
cache.put("A", "B");
assertEquals(1, cache.size());
cache.put("B", "B");
assertEquals(2, cache.size());
cache.remove("B");
cache.remove("A");
assertEquals(0, cache.size());
}
}
@@ -0,0 +1,62 @@
package io.ebeaninternal.server.cache;
import io.ebean.cache.ServerCacheConfig;
import io.ebean.cache.ServerCacheOptions;
import io.ebean.cache.ServerCacheStatistics;
import io.ebean.cache.ServerCacheType;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import java.util.Random;
public class DefaultServerCache_RunEvictionTest {
private DefaultServerCache createCache() {
ServerCacheOptions cacheOptions = new ServerCacheOptions();
cacheOptions.setMaxSize(10000);
cacheOptions.setMaxIdleSecs(1);
cacheOptions.setMaxSecsToLive(2);
cacheOptions.setTrimFrequency(1);
ServerCacheConfig con = new ServerCacheConfig(ServerCacheType.BEAN, "foo", "foo", cacheOptions, null, null);
return new DefaultServerCache(new DefaultServerCacheConfig(con));
}
private final DefaultServerCache cache;
private final Random random = new Random();
public DefaultServerCache_RunEvictionTest() {
this.cache = createCache();
}
@Disabled("test takes long time")
@Test
public void runEvict() throws InterruptedException {
for (int i = 0; i < 15; i++) {
doStuff();
cache.runEviction();
ServerCacheStatistics statistics = cache.statistics(true);
System.out.println(statistics);
Thread.sleep(500);
}
}
private void doStuff() {
for (int i = 0; i < 500; i++) {
String key = "" + random.nextInt(20000);
int mode = random.nextInt(10);
if (mode < 8) {
cache.get(key);
} else {
cache.put(key, key + "-" + System.currentTimeMillis());
}
}
}
}
@@ -0,0 +1,36 @@
package io.ebeaninternal.server.core;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BasicTypeConverterTest {
@Test
public void toBoolean_when_1_long() throws Exception {
Assertions.assertTrue(BasicTypeConverter.toBoolean(1L, "T"));
}
@Test
public void toBoolean_when_1_int() throws Exception {
assertTrue(BasicTypeConverter.toBoolean(1, "T"));
}
@Test
public void toBoolean_when_0() throws Exception {
assertFalse(BasicTypeConverter.toBoolean(0L, "T"));
}
@Test
public void toBoolean_when_TrueValue() throws Exception {
assertTrue(BasicTypeConverter.toBoolean("T", "T"));
}
@Test
public void toBoolean_when_notTrueValue() throws Exception {
assertFalse(BasicTypeConverter.toBoolean("F", "T"));
}
}
@@ -0,0 +1,51 @@
package io.ebeaninternal.server.core;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BindPaddingTest {
@Test
public void padIds() {
final List<Object> input = asList(1, 2);
BindPadding.padIds(input);
assertThat(input).contains(1,2,1,1,1);
assertThat(input).hasSize(5);
}
private List<Object> asList(int... id) {
List<Object> list = new ArrayList<>();
for (int i : id) {
list.add(i);
}
return list;
}
@Test
public void padding() {
assertEquals(0, BindPadding.padding(0));
assertEquals(0, BindPadding.padding(1));
assertEquals(3, BindPadding.padding(2));
assertEquals(2, BindPadding.padding(3));
assertEquals(1, BindPadding.padding(4));
assertEquals(0, BindPadding.padding(5));
assertEquals(4, BindPadding.padding(6));
assertEquals(1, BindPadding.padding(9));
assertEquals(0, BindPadding.padding(10));
assertEquals(9, BindPadding.padding(11));
assertEquals(0, BindPadding.padding(20));
assertEquals(19, BindPadding.padding(21));
assertEquals(0, BindPadding.padding(40));
assertEquals(9, BindPadding.padding(41));
assertEquals(0, BindPadding.padding(50));
assertEquals(49, BindPadding.padding(51));
assertEquals(0, BindPadding.padding(100));
assertEquals(0, BindPadding.padding(101));
}
}
@@ -0,0 +1,23 @@
package io.ebeaninternal.server.core;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DtoQueryRequestTest {
@Test
public void testParse() {
Assertions.assertEquals("foo", DtoQueryRequest.parseColumn("foo"));
assertEquals("bar", DtoQueryRequest.parseColumn("zx__t0_bar"));
assertEquals("BAR", DtoQueryRequest.parseColumn("ZX__T0_BAR"));
assertEquals("baz", DtoQueryRequest.parseColumn("zx__t42_baz"));
assertEquals("BAZ", DtoQueryRequest.parseColumn("ZX__T42_BAZ"));
assertEquals("e_t42_nope", DtoQueryRequest.parseColumn("e_t42_nope"));
assertEquals("_f_t42_nope", DtoQueryRequest.parseColumn("_f_t42_nope"));
}
}
@@ -0,0 +1,188 @@
package io.ebeaninternal.server.core;
import io.ebean.config.DatabaseConfig;
import io.ebean.datasource.DataSourceAlert;
import io.ebean.datasource.DataSourceConfig;
import io.ebean.datasource.pool.ConnectionPool;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class InitDataSourceTest {
private DatabaseConfig newConfig(String readOnlyUrl) {
DatabaseConfig config = new DatabaseConfig();
DataSourceConfig roConfig = new DataSourceConfig();
roConfig.setUrl(readOnlyUrl);
config.setReadOnlyDataSourceConfig(roConfig);
return config;
}
@Test
public void readOnlyConfig_nullByDefault() {
InitDataSource init = new InitDataSource(new DatabaseConfig());
assertNull(init.readOnlyConfig());
}
@Test
public void readOnlyConfig_null_whenSetNullExplicitly() {
DatabaseConfig config = new DatabaseConfig();
config.setReadOnlyDataSourceConfig(null);
assertNull(new InitDataSource(config).readOnlyConfig());
}
@Test
public void readOnlyConfig_null_whenSetNullExplicitly_2() {
assertNull(new InitDataSource(newConfig(null)).readOnlyConfig());
assertNull(new InitDataSource(newConfig("")).readOnlyConfig());
assertNull(new InitDataSource(newConfig(" ")).readOnlyConfig());
}
@Test
public void readOnlyConfig_null_whenValueNONE() {
assertNull(new InitDataSource(newConfig("none")).readOnlyConfig());
assertNull(new InitDataSource(newConfig("None")).readOnlyConfig());
assertNull(new InitDataSource(newConfig("NONE")).readOnlyConfig());
}
@Test
public void readOnlyConfig_when_autoReadOnlyDataSource() {
DatabaseConfig config = new DatabaseConfig();
config.setAutoReadOnlyDataSource(true);
assertNotNull(new InitDataSource(config).readOnlyConfig());
}
@Test
public void readOnlyConfig_when_autoReadOnlyDataSource_expect_setToNull() {
DatabaseConfig config = newConfig("none");
config.setAutoReadOnlyDataSource(true);
final DataSourceConfig readOnlyConfig = new InitDataSource(config).readOnlyConfig();
assertNull(readOnlyConfig.getUrl());
}
@Test
public void readOnlyConfig_when_urlSet() {
DatabaseConfig config = newConfig("foo");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNotNull(roConfig);
assertEquals("foo", roConfig.getUrl());
}
@Test
public void readOnlyConfig_when_readOnlyUrlSetOnMain() {
DatabaseConfig config = newConfig(null);
// alternate location to set read-only url for developer convenience
config.getDataSourceConfig().setReadOnlyUrl("bar");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNotNull(roConfig);
assertEquals("bar", roConfig.getUrl());
}
@Test
public void readOnlyConfig_when_readOnlyUrlSetOnMain_withNone() {
DatabaseConfig config = newConfig("None");
// alternate location to set read-only url for developer convenience
config.getDataSourceConfig().setReadOnlyUrl("bar");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNotNull(roConfig);
assertEquals("bar", roConfig.getUrl());
}
@Test
public void readOnlyConfig_when_bothReadOnlyUrlsSet() {
DatabaseConfig config = newConfig("one");
config.getDataSourceConfig().setReadOnlyUrl("two");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNotNull(roConfig);
assertEquals("one", roConfig.getUrl());
}
@Test
public void readOnlyConfig_when_readOnlyUrlSetOnMain_withNoneNone() {
DatabaseConfig config = newConfig("none");
// alternate location to set read-only url for developer convenience
config.getDataSourceConfig().setReadOnlyUrl("none");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNull(roConfig);
}
@Test
public void readOnlyConfig_when_urlSet_2() {
DatabaseConfig config = new DatabaseConfig();
config.getReadOnlyDataSourceConfig().setUrl("foo");
final DataSourceConfig roConfig = new InitDataSource(config).readOnlyConfig();
assertNotNull(roConfig);
assertEquals("foo", roConfig.getUrl());
}
@Test
public void online() {
DatabaseConfig config = new DatabaseConfig();
config.getDataSourceConfig().setUsername("sa");
config.getDataSourceConfig().setPassword("");
config.getDataSourceConfig().setUrl("jdbc:h2:mem:dsTestOnline");
config.getDataSourceConfig().setDriver("org.h2.Driver");
InitDataSource.init(config);
ConnectionPool pool = (ConnectionPool) config.getDataSource();
assertThat(pool.isDataSourceUp()).isTrue();
pool.shutdown();
}
static class MyAlert implements DataSourceAlert {
int up;
@Override
public void dataSourceUp(DataSource dataSource) {
up++;
}
@Override
public void dataSourceDown(DataSource dataSource, SQLException reason) {
}
@Override
public void dataSourceWarning(DataSource dataSource, String msg) {
}
}
@Test
public void offline() throws SQLException {
DatabaseConfig config = new DatabaseConfig();
config.getDataSourceConfig().setUsername("sa");
config.getDataSourceConfig().setPassword("");
config.getDataSourceConfig().setUrl("jdbc:h2:mem:dsTestOffline");
config.getDataSourceConfig().setDriver("org.h2.Driver");
config.getDataSourceConfig().setOffline(true);
config.getDataSourceConfig().setFailOnStart(false);
MyAlert alert = new MyAlert();
config.getDataSourceConfig().setAlert(alert);
config.setDatabasePlatformName("h2");
InitDataSource.init(config);
ConnectionPool pool = (ConnectionPool) config.getDataSource();
assertThat(pool).isNotNull();
// make some additional tests with the pool
assertThat(pool.isDataSourceUp()).isFalse();
assertThat(alert.up).isEqualTo(0);
pool.online();
assertThat(alert.up).isEqualTo(1);
assertThat(pool.isDataSourceUp()).isTrue();
pool.shutdown();
}
}
@@ -0,0 +1,52 @@
package io.ebeaninternal.server.core.bootup;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class DistillPackagesTest {
@Test
public void when_unique_expect_all() throws Exception {
List<String> distill = DistillPackages.distill(group("one", "two"), group("three"));
assertThat(distill).containsExactly("one", "three", "two");
}
@Test
public void when_sub_expect_distilled() throws Exception {
List<String> distill = DistillPackages.distill(group("one", "one.sub"), group("three"));
assertThat(distill).containsExactly("one", "three");
}
@Test
public void when_sub_expect_distilled2() throws Exception {
List<String> distill = DistillPackages.distill(group("one", "one.sub"), group("one.foo"));
assertThat(distill).containsExactly("one");
}
@Test
public void when_subDotSub_expect_distilled2() throws Exception {
List<String> distill = DistillPackages.distill(group("one", "one.sub.me"), group("two"));
assertThat(distill).containsExactly("one", "two");
}
@Test
public void when_unordered_expect_naturalOrder() throws Exception {
List<String> distill = DistillPackages.distill(group("z.x.y", "two"), group("one", "one.sub.me"));
assertThat(distill).containsExactly("one", "two", "z.x.y");
}
List<String> group(String... packages) {
return Arrays.asList(packages);
}
}
@@ -0,0 +1,53 @@
package io.ebeaninternal.server.core.bootup;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class ManifestReaderTest {
@Test
public void readOne() throws Exception {
Set<String> packageSet = readMf("META-INF/test/test-one.mf");
assertThat(packageSet).contains("foo");
}
@Test
public void readSome() throws Exception {
Set<String> packageSet = readMf("META-INF/test/test-some.mf");
assertThat(packageSet).contains("com.foo.domain", "com.bar.domain");
}
@Test
public void readEntityPackages() throws Exception {
Set<String> packageSet = readMf("META-INF/test/test-entity-packages.mf");
assertThat(packageSet).contains("com.baz", "org.bax.domain");
}
@Test
public void readCombined() throws Exception {
Set<String> packageSet = readMf("META-INF/test/test-combined.mf");
assertThat(packageSet).contains("com.foo.domain", "com.bar.domain", "com.baz.domain");
}
@Test
public void readAgentOnlyUse() throws Exception {
Set<String> packageSet = readMf("META-INF/test/test-agent-only-use.mf");
assertThat(packageSet).isEmpty();
}
private Set<String> readMf(String path) {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return ManifestReader.create(classLoader)
.read(path)
.entityPackages();
}
}
@@ -0,0 +1,82 @@
package io.ebeaninternal.server.deploy;
import org.junit.jupiter.api.Test;
import javax.persistence.CascadeType;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class BeanCascadeInfoTest {
@Test
public void setTypes_ALL() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setTypes(new CascadeType[]{CascadeType.ALL});
assertTrue(info.isSave());
assertTrue(info.isDelete());
assertTrue(info.isRefresh());
}
@Test
public void setTypes_PERSIST() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setTypes(new CascadeType[]{CascadeType.PERSIST});
assertTrue(info.isSave());
assertFalse(info.isDelete());
assertFalse(info.isRefresh());
}
@Test
public void setTypes_MERGE() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setTypes(new CascadeType[]{CascadeType.MERGE});
assertTrue(info.isSave());
assertFalse(info.isDelete());
assertFalse(info.isRefresh());
}
@Test
public void setTypes_REMOVE() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setTypes(new CascadeType[]{CascadeType.REMOVE});
assertFalse(info.isSave());
assertTrue(info.isDelete());
assertFalse(info.isRefresh());
}
@Test
public void setTypes_REFRESH() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setTypes(new CascadeType[]{CascadeType.REFRESH});
assertFalse(info.isSave());
assertFalse(info.isDelete());
assertTrue(info.isRefresh());
}
@Test
public void setDelete() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setDelete(true);
assertFalse(info.isSave());
assertTrue(info.isDelete());
assertFalse(info.isRefresh());
}
@Test
public void setSaveDelete() throws Exception {
BeanCascadeInfo info = new BeanCascadeInfo();
info.setSaveDelete(true, true);
assertTrue(info.isSave());
assertTrue(info.isDelete());
assertFalse(info.isRefresh());
}
}
@@ -0,0 +1,77 @@
package io.ebeaninternal.server.deploy;
import io.ebean.meta.BasicMetricVisitor;
import io.ebean.meta.MetaTimedMetric;
import io.ebeaninternal.server.core.PersistRequest;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
public class BeanIudMetricsTest {
@Test
public void addBatch() {
BeanIudMetrics iudMetrics = new BeanIudMetrics("one");
final long startNanos = System.nanoTime() - 10000;
iudMetrics.addBatch(PersistRequest.Type.INSERT, startNanos, 4);
BasicMetricVisitor basic = new BasicMetricVisitor();
iudMetrics.visit(basic);
List<MetaTimedMetric> timed = basic.timedMetrics();
assertThat(timed).hasSize(1);
assertThat(timed.get(0).count()).isEqualTo(4);
assertThat(timed.get(0).name()).isEqualTo("iud.one.insertBatch");
iudMetrics.addBatch(PersistRequest.Type.UPDATE, startNanos, 1);
iudMetrics.addBatch(PersistRequest.Type.DELETE_SOFT, startNanos, 2);
iudMetrics.addBatch(PersistRequest.Type.DELETE, startNanos, 4);
iudMetrics.addBatch(PersistRequest.Type.DELETE_PERMANENT, startNanos, 8);
iudMetrics.addBatch(PersistRequest.Type.INSERT, startNanos, 16);
basic = new BasicMetricVisitor();
iudMetrics.visit(basic);
timed = basic.timedMetrics();
assertThat(timed).hasSize(3);
assertThat(timed.get(0).count()).isEqualTo(16);
assertThat(timed.get(0).name()).isEqualTo("iud.one.insertBatch");
assertThat(timed.get(1).count()).isEqualTo(3);
assertThat(timed.get(1).name()).isEqualTo("iud.one.updateBatch");
assertThat(timed.get(2).count()).isEqualTo(12);
assertThat(timed.get(2).name()).isEqualTo("iud.one.deleteBatch");
}
@Test
public void addNoBatch() {
BeanIudMetrics iudMetrics = new BeanIudMetrics("one");
final long startNanos = System.nanoTime() - 10000;
iudMetrics.addNoBatch(PersistRequest.Type.INSERT, startNanos);
iudMetrics.addNoBatch(PersistRequest.Type.UPDATE, startNanos);
iudMetrics.addNoBatch(PersistRequest.Type.DELETE_SOFT, startNanos);
iudMetrics.addNoBatch(PersistRequest.Type.DELETE, startNanos);
iudMetrics.addNoBatch(PersistRequest.Type.DELETE_PERMANENT, startNanos);
BasicMetricVisitor basic = new BasicMetricVisitor();
iudMetrics.visit(basic);
List<MetaTimedMetric> timed = basic.timedMetrics();
assertThat(timed).hasSize(3);
assertThat(timed.get(0).count()).isEqualTo(1);
assertThat(timed.get(0).name()).isEqualTo("iud.one.insert");
assertThat(timed.get(1).count()).isEqualTo(2);
assertThat(timed.get(1).name()).isEqualTo("iud.one.update");
assertThat(timed.get(2).count()).isEqualTo(2);
assertThat(timed.get(2).name()).isEqualTo("iud.one.delete");
}
}
@@ -0,0 +1,26 @@
package io.ebeaninternal.server.deploy;
import org.junit.jupiter.api.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DeployPropertyParserMapTests {
@Test
public void test_like_escape() {
Map<String, String> map = new HashMap<>();
map.put("customer.name", "t1.name");
map.put("id", "t0.id");
DeployPropertyParserMap parser = new DeployPropertyParserMap(map);
String output = parser.parse("(lower(customer.name) like ? escape'' or id > ?)");
assertEquals("(lower(t1.name) like ? escape'' or t0.id > ?)", output);
}
}
@@ -0,0 +1,35 @@
package io.ebeaninternal.server.deploy;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DetermineAggPathTest {
@Test
public void path() throws Exception {
Assertions.assertThat(DetermineAggPath.path("count(details)")).isEqualTo("details");
assertThat(DetermineAggPath.path("count(details )")).isEqualTo("details");
assertThat(DetermineAggPath.path("count(person.contacts)")).isEqualTo("person.contacts");
assertThat(DetermineAggPath.path("sum(details.quantity*details.unitPrice)")).isEqualTo("details.quantity");
}
@Test
public void paths_simple() throws Exception {
DetermineAggPath.Path paths = DetermineAggPath.paths("count(details)");
assertThat(paths.paths).isEqualTo(new String[]{"details"});
}
@Test
public void paths_nested() throws Exception {
DetermineAggPath.Path paths = DetermineAggPath.paths("count(person.contacts)");
assertThat(paths.paths).isEqualTo(new String[]{"person", "contacts"});
}
}
@@ -0,0 +1,43 @@
package io.ebeaninternal.server.deploy;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class IndexDefinitionTest {
private static final String[] simpleCol1 = new String[]{"one"};
private static final String[] simpleCol2 = new String[]{"one","two"};
private static final String[] formulaCol1 = new String[]{"lower(one)"};
private static final String[] formulaCol2 = new String[]{"one","lower(two)"};
@Test
public void isUniqueConstraint_TRUE_when_simpleMultiColumn() {
Assertions.assertTrue(new IndexDefinition(simpleCol1).isUniqueConstraint());
assertTrue(new IndexDefinition(simpleCol2).isUniqueConstraint());
}
@Test
public void isUniqueConstraint_NOT_when_columnWithFormula() {
assertFalse(new IndexDefinition(formulaCol1).isUniqueConstraint());
assertFalse(new IndexDefinition(formulaCol2).isUniqueConstraint());
}
@Test
public void isUniqueConstraint_NOT_when_concurrentTrue() {
assertFalse(new IndexDefinition(simpleCol1, "name", true, null, true, null).isUniqueConstraint());
}
@Test
public void isUniqueConstraint_NOT_when_definitionNotEmpty() {
assertFalse(new IndexDefinition(simpleCol1, "name", true, null, false, "create index foo").isUniqueConstraint());
}
@Test
public void isUniqueConstraint_TRUE_otherwise() {
assertTrue(new IndexDefinition(simpleCol1, "name", true, null, false, "").isUniqueConstraint());
assertTrue(new IndexDefinition(simpleCol1, "name", true, null, false, null).isUniqueConstraint());
}
}
@@ -0,0 +1,49 @@
package io.ebeaninternal.server.deploy;
import io.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TableJoinColumnTest {
TableJoinColumn col(String localDbColumn, String foreignDbColumn, boolean insertable, boolean updateable) {
DeployTableJoinColumn column = new DeployTableJoinColumn(localDbColumn, foreignDbColumn, insertable, updateable);
return new TableJoinColumn(column);
}
@Test
public void equals_when_same() {
assertSame(col("a", "b", true, true), col("a", "b", true, true));
}
@Test
public void equals_when_diffFirstCol() {
assertDifferent(col("a", "b", true, true), col("c", "b", true, true));
}
@Test
public void equals_when_diffSecondCol() {
assertDifferent(col("a", "b", true, true), col("a", "c", true, true));
}
@Test
public void equals_when_diffInsertable() {
assertDifferent(col("a", "b", true, true), col("a", "b", false, true));
}
@Test
public void equals_when_diffUpdateable() {
assertDifferent(col("a", "b", true, true), col("a", "b", true, false));
}
private void assertDifferent(TableJoinColumn col, TableJoinColumn col2) {
assertThat(col).isNotEqualTo(col2);
assertThat(col.hashCode()).isNotEqualTo(col2.hashCode());
}
private void assertSame(TableJoinColumn col, TableJoinColumn col2) {
assertThat(col).isEqualTo(col2);
assertThat(col.hashCode()).isEqualTo(col2.hashCode());
}
}
@@ -0,0 +1,67 @@
package io.ebeaninternal.server.deploy;
import io.ebeaninternal.server.deploy.meta.DeployTableJoin;
import io.ebeaninternal.server.deploy.meta.DeployTableJoinColumn;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class TableJoinTest {
DeployTableJoinColumn col(String localDbColumn, String foreignDbColumn, boolean insertable, boolean updateable) {
return new DeployTableJoinColumn(localDbColumn, foreignDbColumn, insertable, updateable);
}
TableJoin table(String tableName, String col1, String col2) {
DeployTableJoin deploy = new DeployTableJoin();
deploy.setTable(tableName);
deploy.addJoinColumn(col(col1, col2, true, true));
return new TableJoin(deploy);
}
TableJoin table(String tableName, String col1, String col2, String col3, String col4) {
DeployTableJoin deploy = new DeployTableJoin();
deploy.setTable(tableName);
deploy.addJoinColumn(col(col1, col2, true, true));
deploy.addJoinColumn(col(col3, col4, true, true));
return new TableJoin(deploy);
}
@Test
public void equals_when_same() {
assertSame(table("myTable", "a", "b"), table("myTable", "a", "b"));
}
@Test
public void equals_when_diffTable() {
assertDifferent(table("myTable", "a", "b"), table("diffTable", "a", "b"));
}
@Test
public void equals_when_diffColumn() {
assertDifferent(table("myTable", "a", "b"), table("myTable", "c", "b"));
}
@Test
public void equals_when_moreColumns() {
assertDifferent(table("myTable", "a", "b"), table("myTable", "a", "b", "c", "d"));
}
@Test
public void equals_when_lessColumns() {
assertDifferent(table("myTable", "a", "b", "c", "d"), table("myTable", "a", "b"));
}
void assertSame(TableJoin join1, TableJoin join2) {
assertThat(join1).isEqualTo(join1);
assertThat(join1.hashCode()).isEqualTo(join1.hashCode());
}
void assertDifferent(TableJoin join1, TableJoin join2) {
assertThat(join1).isNotEqualTo(join2);
assertThat(join1.hashCode()).isNotEqualTo(join2.hashCode());
}
}
@@ -0,0 +1,34 @@
package io.ebeaninternal.server.deploy.generatedproperty;
import io.ebeaninternal.server.deploy.BeanProperty;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
class GeneratedCounterLongTest {
private final GeneratedCounterLong counter = new GeneratedCounterLong();
@Test
void when_null_expect_IllegalStateException() {
BeanProperty beanProperty = mock(BeanProperty.class);
when(beanProperty.getValue(any())).thenReturn(null);
assertThrows(IllegalStateException.class, () -> counter.getUpdateValue(beanProperty, null, System.currentTimeMillis()));
}
@Test
void when_set_expect_incremented() {
BeanProperty beanProperty = mock(BeanProperty.class);
when(beanProperty.getValue(any())).thenReturn(7L);
Object value = counter.getUpdateValue(beanProperty, null, System.currentTimeMillis());
assertThat(value).isEqualTo(8L);
}
}
@@ -0,0 +1,17 @@
package io.ebeaninternal.server.deploy.generatedproperty;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class GeneratedInsertJavaTimeTest {
@Test
public void test_generatedOnInsert() {
GeneratedProperty gen = new GeneratedInsertJavaTime.InstantDT();
assertTrue(GeneratedWhenCreated.class.isInstance(gen));
assertTrue(gen instanceof GeneratedWhenCreated);
}
}
@@ -0,0 +1,68 @@
package io.ebeaninternal.server.deploy.generatedproperty;
import io.ebean.config.ClassLoadConfig;
import io.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class InsertTimestampFactoryTest {
InsertTimestampFactory factory = new InsertTimestampFactory(new ClassLoadConfig());
@Test
public void test_createdTimestamp_Instant() {
DeployBeanProperty prop = new DeployBeanProperty(null, Instant.class, null, null);
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof Instant);
}
@Test
public void test_createdTimestamp_LocalDateTime() {
DeployBeanProperty prop = new DeployBeanProperty(null, LocalDateTime.class, null, null);
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof LocalDateTime);
}
@Test
public void test_createdTimestamp_OffsetDateTime() {
DeployBeanProperty prop = new DeployBeanProperty(null, OffsetDateTime.class, null, null);
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof OffsetDateTime);
}
@Test
public void test_createdTimestamp_Timestamp() {
DeployBeanProperty prop = new DeployBeanProperty(null, Timestamp.class, null, null);
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof Timestamp);
}
@Test
public void test_createdTimestamp_utilDate() {
DeployBeanProperty prop = new DeployBeanProperty(null, java.util.Date.class, null, null);
GeneratedProperty insertTimestamp = factory.createInsertTimestamp(prop);
Object value = insertTimestamp.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof java.util.Date);
}
}
@@ -0,0 +1,68 @@
package io.ebeaninternal.server.deploy.generatedproperty;
import io.ebean.config.ClassLoadConfig;
import io.ebeaninternal.server.deploy.meta.DeployBeanProperty;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class UpdateTimestampFactoryTest {
UpdateTimestampFactory factory = new UpdateTimestampFactory(new ClassLoadConfig());
@Test
public void test_createdTimestamp_Instant() {
DeployBeanProperty prop = new DeployBeanProperty(null, Instant.class, null, null);
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof Instant);
}
@Test
public void test_createdTimestamp_LocalDateTime() {
DeployBeanProperty prop = new DeployBeanProperty(null, LocalDateTime.class, null, null);
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof LocalDateTime);
}
@Test
public void test_createdTimestamp_OffsetDateTime() {
DeployBeanProperty prop = new DeployBeanProperty(null, OffsetDateTime.class, null, null);
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof OffsetDateTime);
}
@Test
public void test_createdTimestamp_Timestamp() {
DeployBeanProperty prop = new DeployBeanProperty(null, Timestamp.class, null, null);
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof Timestamp);
}
@Test
public void test_createdTimestamp_utilDate() {
DeployBeanProperty prop = new DeployBeanProperty(null, java.util.Date.class, null, null);
GeneratedProperty generatedProperty = factory.createUpdateTimestamp(prop);
Object value = generatedProperty.getInsertValue(null, null, System.currentTimeMillis());
assertTrue(value instanceof java.util.Date);
}
}
@@ -0,0 +1,64 @@
package io.ebeaninternal.server.deploy.parse;
import io.ebean.config.DatabaseConfig;
import io.ebean.config.dbplatform.sqlserver.SqlServer17Platform;
import io.ebeaninternal.server.core.bootup.BootupClasses;
import io.ebeaninternal.server.deploy.generatedproperty.GeneratedPropertyFactory;
import io.ebeaninternal.server.deploy.meta.DeployBeanDescriptor;
import io.ebeaninternal.server.type.DefaultTypeManager;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
public class AnnotationClassTest {
@Test
public void convertColumnNames_when_AllQuotedIdentifiersIsTrue() {
AnnotationClass annotationClass = createAnnotationClass(sqlServerPlatform(true));
String[] colNames = {"Col1", "Col2"};
final String[] columnNames = annotationClass.convertColumnNames(colNames);
assertThat(columnNames.length).isEqualTo(2);
assertThat(columnNames[0]).isEqualTo("[Col1]");
assertThat(columnNames[1]).isEqualTo("[Col2]");
}
@Test
public void convertColumnNames_when_AllQuotedIdentifiersIsFalse() {
AnnotationClass annotationClass = createAnnotationClass(sqlServerPlatform(false));
String[] colNames = {"Col1", "`Col2`", "col3"};
final String[] columnNames = annotationClass.convertColumnNames(colNames);
assertThat(columnNames.length).isEqualTo(3);
assertThat(columnNames[0]).isEqualTo("Col1");
assertThat(columnNames[1]).isEqualTo("[Col2]");
assertThat(columnNames[2]).isEqualTo("col3");
}
@SuppressWarnings({"unchecked", "rawtypes"})
private AnnotationClass createAnnotationClass(DatabaseConfig config) {
DeployUtil deployUtil = new DeployUtil(new DefaultTypeManager(config, new BootupClasses()), config);
DeployBeanInfo deployBeanInfo = new DeployBeanInfo(deployUtil, new DeployBeanDescriptor<>(null, null, null));
ReadAnnotationConfig readAnnotationConfig = new ReadAnnotationConfig(new GeneratedPropertyFactory(true, new DatabaseConfig(), Collections.emptyList()), "","", new DatabaseConfig());
return new AnnotationClass(deployBeanInfo, readAnnotationConfig);
}
private DatabaseConfig sqlServerPlatform(boolean allQuotedIdentifiers) {
SqlServer17Platform sqlServer17Platform = new SqlServer17Platform();
DatabaseConfig config = new DatabaseConfig();
config.setDatabasePlatform(sqlServer17Platform);
config.setAllQuotedIdentifiers(allQuotedIdentifiers);
sqlServer17Platform.configure(config.getPlatformConfig());
return config;
}
}
@@ -0,0 +1,123 @@
package io.ebeaninternal.server.dto;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
public class DtoMetaBuilderTest {
@Test
public void includeMethod() {
Map<String, Method> methods = getIncludedMethodsFor(D0.class);
assertThat(methods).hasSize(2);
assertThat(methods.get("setName")).isNotNull();
assertThat(methods.get("setId")).isNotNull();
}
@Test
public void includeMethod_when_notStrictlySetters() {
Map<String, Method> methods = getIncludedMethodsFor(D1.class);
assertThat(methods).hasSize(3);
assertThat(methods.get("setNameThen")).isNotNull();
assertThat(methods.get("setIdFor")).isNotNull();
assertThat(methods.get("setI")).isNotNull();
}
@Test
public void propertyType() {
Map<String, Method> methods = getIncludedMethodsFor(D0.class);
assertThat(methods).hasSize(2);
Assertions.assertThat(DtoMetaProperty.propertyClass(methods.get("setName"))).isEqualTo(String.class);
assertThat(DtoMetaProperty.propertyClass(methods.get("setId"))).isEqualTo(long.class);
assertThat(DtoMetaProperty.propertyType(methods.get("setName"))).isEqualTo(String.class);
assertThat(DtoMetaProperty.propertyType(methods.get("setId"))).isEqualTo(long.class);
}
@Test
public void propertyName() {
Assertions.assertThat(DtoMetaBuilder.propertyName("setName")).isEqualTo("name");
assertThat(DtoMetaBuilder.propertyName("setId")).isEqualTo("id");
assertThat(DtoMetaBuilder.propertyName("setI")).isEqualTo("i");
assertThat(DtoMetaBuilder.propertyName("setfoo")).isEqualTo("foo");
}
private Map<String, Method> getIncludedMethodsFor(Class<?> cls) {
Map<String,Method> included = new HashMap<>();
for (Method method : cls.getMethods()) {
if (DtoMetaBuilder.includeMethod(method)) {
included.put(method.getName(), method);
}
}
return included;
}
@SuppressWarnings("unused")
static class D0 {
private String name;
private long id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setId(long id) {
this.id = id;
}
public void setNamePlus(String name, long id) {
this.name = name;
this.id = id;
}
public static void setFoo(String foo) {
}
protected void setProtected(String foo) {
}
private void setPrivate(String foo) {
}
private void setPackage(String foo) {
}
}
@SuppressWarnings("unused")
static class D1 {
public void setNameThen(String name) {
}
public void setIdFor(long id) {
}
public void setI(long val) {
}
public void set(long val) {
}
public D1 setA(long val) {
return this;
}
}
}
@@ -0,0 +1,166 @@
package io.ebeaninternal.server.executor;
import io.ebean.config.MdcBackgroundExecutorWrapper;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.slf4j.MDC;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DefaultBackgroundExecutorTest {
@Test
public void submit_callable() throws Exception {
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, 2, "test", null);
final Future<String> future0 = es.submit(() -> "Hello");
final Future<String> future1 = es.submit(() -> "There");
final Future<String> future2 = es.submit(() -> {
try {
Thread.sleep(100);
return "Slow";
} catch (InterruptedException e) {
e.printStackTrace();
return "Interrupted";
}
});
es.shutdown();
assertThat(future0.get()).isEqualTo("Hello");
assertThat(future1.get(1, TimeUnit.SECONDS)).isEqualTo("There");
assertThat(future2.get()).isEqualTo("Slow");
}
@Test
public void shutdown_slowCallable_expect_interrupted() throws Exception {
int shutdownWaitSecs = 1;
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, shutdownWaitSecs, "test", null);
final Future<String> future2 = es.submit(() -> {
try {
Thread.sleep(1500); // longer than shutdown wait
return "Slow";
} catch (InterruptedException e) {
// expected for this test
Thread.currentThread().interrupt();
return "Interrupted";
}
});
// shutdown waits max shutdownWaitSecs seconds for active tasks
es.shutdown();
assertThat(future2.get()).isEqualTo("Interrupted");
}
@Test
@Disabled("test takes long time")
public void shutdown_when_running_expect_waitAndNiceShutdown() {
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, 20, "test", null);
es.execute(new RunFor(3000, "a"));
es.execute(new RunFor(3000, "b"));
es.execute(new RunFor(3000, "c"));
es.shutdown();
}
@Test
@Disabled("test takes long time")
public void shutdown_when_rougeRunnable_expect_InterruptedException() {
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, 10, "test", null);
es.execute(new RunFor(300000, "a"));
es.execute(new RunFor(3000, "b"));
es.execute(new RunFor(3000, "c"));
es.shutdown();
}
@Test
public void wrapWithNoMDC() {
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, 10, "test", null);
assertThat(MDC.getCopyOfContextMap()).isNull();
es.wrap(() -> {
assertThat(MDC.getCopyOfContextMap()).isNull();
});
es.wrap(() -> {
assertThat(MDC.getCopyOfContextMap()).isNull();
return "Callable";
});
es.shutdown();
}
@Test
public void wrapWithMDC_expect_() throws Exception {
DefaultBackgroundExecutor es = new DefaultBackgroundExecutor(1, 10, "test", new MdcBackgroundExecutorWrapper());
// MDC has a copyOnThread map. So we must pass different values to check if the test will work
MDC.clear();
es.submit(()->{
assertThat(MDC.get("hello")).isNull();
}).get();
MDC.put("hello", "there");
es.wrap(() -> {
assertThat(MDC.get("hello")).isEqualTo("there");
}).run(); // will clear the MDC. But this should be OK
MDC.put("hello", "there");
es.wrap(() -> {
assertThat(MDC.get("hello")).isEqualTo("there");
return "Callable";
}).call(); // will clear the MDC. But this should be OK
MDC.put("hello", "there");
CountDownLatch latch = new CountDownLatch(1);
es.execute(() -> {
// the assertion is executed async, so it will only logged on console
assertThat(MDC.get("hello")).isEqualTo("there");
latch.countDown();
});
assertTrue(latch.await(5, TimeUnit.SECONDS));
es.submit(() -> {
assertThat(MDC.get("hello")).isEqualTo("there");
return "Callable";
}).get();
MDC.clear();
es.execute(()->{
assertThat(MDC.get("hello")).isNull();
});
es.shutdown();
}
private static class RunFor implements Runnable {
final long wait;
final String id;
RunFor(long wait, String id) {
this.wait = wait;
this.id = id;
}
@Override
public void run() {
try {
System.out.println("start " + id);
Thread.sleep(wait);
System.out.println("done " + id);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@@ -0,0 +1,18 @@
package io.ebeaninternal.server.expression.platform;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class H2DbExpressionTest {
H2DbExpression expression = new H2DbExpression();
@Test
public void concat() {
assertThat(expression.concat("p0", ",", "q1", "suffix")).isEqualTo("concat(p0,',',q1,'suffix')");
assertThat(expression.concat("p0", ",", "q1", null)).isEqualTo("concat(p0,',',q1)");
assertThat(expression.concat("p0", ",", "q1", "")).isEqualTo("concat(p0,',',q1)");
}
}
@@ -0,0 +1,69 @@
package io.ebeaninternal.server.expression.platform;
import io.ebeaninternal.api.SpiExpressionRequest;
import io.ebeaninternal.server.expression.DefaultExpressionRequest;
import io.ebeaninternal.server.expression.Op;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class HanaDbExpressionTest {
private HanaDbExpression expression = new HanaDbExpression();
@Test
public void testArrayContains() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.arrayContains(request, "arrayproperty", true, "v1", "v2", "v3");
assertEquals("(? member of arrayproperty) and (? member of arrayproperty) and (? member of arrayproperty)",
request.getSql());
}
@Test
public void testArrayNotContains() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.arrayContains(request, "arrayproperty", false, "v1", "v2", "v3");
assertEquals(
"(? not member of arrayproperty) and (? not member of arrayproperty) and (? not member of arrayproperty)",
request.getSql());
}
@Test
public void testArrayContainsEmpty() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.arrayContains(request, "arrayproperty", true);
assertEquals("", request.getSql());
}
@Test
public void testArrayIsEmpty() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.arrayIsEmpty(request, "arrayproperty", true);
assertEquals("cardinality(arrayproperty) = 0", request.getSql());
}
@Test
public void testArrayIsNotEmpty() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.arrayIsEmpty(request, "arrayproperty", false);
assertEquals("cardinality(arrayproperty) <> 0", request.getSql());
}
@Test
public void testConcat() {
String concat = expression.concat("property0", "separator", "property1", "suffix");
assertEquals("concat(property0, 'separator'||property1||'suffix')", concat);
}
@Test
public void testConcatNullSuffix() {
String concat = expression.concat("property0", "separator", "property1", null);
assertEquals("concat(property0, 'separator'||property1)", concat);
}
@Test
public void testJson() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.json(request, "jsonproperty", "path", Op.EQ, "val");
assertEquals("json_value(jsonproperty, '$.path') = ?", request.getSql());
}
}
@@ -0,0 +1,20 @@
package io.ebeaninternal.server.expression.platform;
import io.ebeaninternal.api.SpiExpressionRequest;
import io.ebeaninternal.server.expression.DefaultExpressionRequest;
import io.ebeaninternal.server.expression.Op;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class MySqlDbExpressionTest {
private MySqlDbExpression expression = new MySqlDbExpression();
@Test
public void testJson() {
SpiExpressionRequest request = new DefaultExpressionRequest(null);
expression.json(request, "jsonproperty", "path", Op.EQ, "val");
assertEquals("(jsonproperty ->> '$.path') = ?", request.getSql());
}
}
@@ -0,0 +1,18 @@
package io.ebeaninternal.server.expression.platform;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class OracleDbExpressionTest {
OracleDbExpression expression = new OracleDbExpression();
@Test
public void concat() {
assertThat(expression.concat("p0", ",", "q1", "suffix")).isEqualTo("(p0||','||q1||'suffix')");
assertThat(expression.concat("p0", ",", "q1", null)).isEqualTo("(p0||','||q1)");
assertThat(expression.concat("p0", ",", "q1", "")).isEqualTo("(p0||','||q1)");
}
}
@@ -0,0 +1,29 @@
package io.ebeaninternal.server.expression.platform;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PostgresCastTest {
@Test
public void cast() {
Assertions.assertThat(PostgresCast.cast(1)).isEqualTo("::integer");
assertThat(PostgresCast.cast(1L)).isEqualTo("::bigint");
assertThat(PostgresCast.cast(1.0D)).isEqualTo("::decimal");
assertThat(PostgresCast.cast("")).isEqualTo("");
}
@Test
public void cast1() {
assertThat(PostgresCast.cast(1, true)).isEqualTo("::integer[]");
assertThat(PostgresCast.cast(1L, true)).isEqualTo("::bigint[]");
assertThat(PostgresCast.cast(1.0D, true)).isEqualTo("::decimal[]");
assertThat(PostgresCast.cast("", true)).isEqualTo("");
}
}
@@ -0,0 +1,17 @@
package io.ebeaninternal.server.expression.platform;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class PostgresDbExpressionTest {
PostgresDbExpression expression = new PostgresDbExpression();
@Test
public void concat() {
assertThat(expression.concat("p0", ",", "p1", "suffix")).isEqualTo("(p0||','||p1||'suffix')");
assertThat(expression.concat("p0", ",", "p1", null)).isEqualTo("(p0||','||p1)");
assertThat(expression.concat("p0", ",", "p1", "")).isEqualTo("(p0||','||p1)");
}
}
@@ -0,0 +1,42 @@
package io.ebeaninternal.server.grammer;
import io.ebean.FetchConfig;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertNull;
public class ParseFetchConfigTest {
@Test
public void parse() throws Exception {
assertNull(ParseFetchConfig.parse("junk"));
assertNull(ParseFetchConfig.parse("lazyFoo"));
assertNull(ParseFetchConfig.parse("queryFoo"));
}
@Test
public void parseLazy() {
FetchConfig lazy = ParseFetchConfig.parse("lazy");
assertThat(lazy.getBatchSize()).isEqualTo(0);
}
@Test
public void parseLazy100() {
FetchConfig lazy = ParseFetchConfig.parse("lazy(100)");
assertThat(lazy.getBatchSize()).isEqualTo(100);
}
@Test
public void parseQuery() {
FetchConfig lazy = ParseFetchConfig.parse("query");
assertThat(lazy.getBatchSize()).isEqualTo(100);
}
@Test
public void parseQuery100() {
FetchConfig lazy = ParseFetchConfig.parse("query(50)");
assertThat(lazy.getBatchSize()).isEqualTo(50);
}
}
@@ -0,0 +1,48 @@
package io.ebeaninternal.server.persist;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BatchDepthOrderTest {
@Test
public void orderingFor() {
BatchDepthOrder depthOrder = new BatchDepthOrder();
assertEquals(0, depthOrder.orderingFor(0));
assertEquals(1, depthOrder.orderingFor(0));
assertEquals(2, depthOrder.orderingFor(0));
assertEquals(100, depthOrder.orderingFor(1));
assertEquals(101, depthOrder.orderingFor(1));
assertEquals(200, depthOrder.orderingFor(2));
assertEquals(3, depthOrder.orderingFor(0));
assertEquals(-100, depthOrder.orderingFor(-1));
assertEquals(-99, depthOrder.orderingFor(-1));
assertEquals(-98, depthOrder.orderingFor(-1));
assertEquals(-200, depthOrder.orderingFor(-2));
assertEquals(-199, depthOrder.orderingFor(-2));
}
@Test
public void clear() {
BatchDepthOrder depthOrder = new BatchDepthOrder();
assertEquals(0, depthOrder.orderingFor(0));
assertEquals(1, depthOrder.orderingFor(0));
assertEquals(100, depthOrder.orderingFor(1));
assertEquals(101, depthOrder.orderingFor(1));
depthOrder.clear();
assertEquals(0, depthOrder.orderingFor(0));
assertEquals(100, depthOrder.orderingFor(1));
assertEquals(200, depthOrder.orderingFor(2));
}
}
@@ -0,0 +1,48 @@
package io.ebeaninternal.server.profile;
import io.ebean.metric.MetricFactory;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class BasicProfileLocationTest {
@Test
void obtain() {
DProfileLocation loc = new DTimedProfileLocation(12, "foo", MetricFactory.get().createTimedMetric("junk"));
String javaVersion = System.getProperty("java.version");
assertThat(loc.obtain()).isTrue();
if (javaVersion.startsWith("1.8")) {
assertThat(loc.fullLocation()).endsWith("invoke0(Native Method:12)");
assertThat(loc.location()).isEqualTo("sun.reflect.NativeMethodAccessorImpl.invoke0");
assertThat(loc.label()).isEqualTo("NativeMethodAccessorImpl.invoke0");
} else if (javaVersion.startsWith("18") || javaVersion.startsWith("19")){
assertThat(loc.fullLocation()).endsWith("jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:104)");
assertThat(loc.location()).isEqualTo("java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke");
assertThat(loc.label()).isEqualTo("DirectMethodHandleAccessor.invoke");
} else {
assertThat(loc.fullLocation()).endsWith("jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method:12)");
assertThat(loc.location()).isEqualTo("java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0");
assertThat(loc.label()).isEqualTo("NativeMethodAccessorImpl.invoke0");
}
}
@Test
void basic_trimPackage() {
BasicProfileLocation loc = new BasicProfileLocation("com.foo.Bar.all");
assertThat(loc.obtain()).isFalse();
assertThat(loc.fullLocation()).isEqualTo("com.foo.Bar.all");
assertThat(loc.location()).isEqualTo("com.foo.Bar.all");
assertThat(loc.label()).isEqualTo("Bar.all");
}
@Test
void basic_trimSinglePackage() {
BasicProfileLocation loc = new BasicProfileLocation("foo.Bar.all");
assertThat(loc.obtain()).isFalse();
assertThat(loc.fullLocation()).isEqualTo("foo.Bar.all");
assertThat(loc.location()).isEqualTo("foo.Bar.all");
assertThat(loc.label()).isEqualTo("Bar.all");
}
}
@@ -0,0 +1,37 @@
package io.ebeaninternal.server.profile;
import io.ebean.meta.BasicMetricVisitor;
import io.ebean.meta.MetaTimedMetric;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DTimedMetricMapTest {
@Test
public void addSinceNanos() throws InterruptedException {
DTimedMetricMap metricMap = new DTimedMetricMap("addSinceNanos");
long nanos = System.nanoTime();
Thread.sleep(10);
metricMap.addSinceNanos("some", nanos);
BasicMetricVisitor visitor = new BasicMetricVisitor();
metricMap.visit(visitor);
MetaTimedMetric timedMetric = visitor.timedMetrics().get(0);
assertThat(timedMetric.count()).isEqualTo(1);
assertThat(timedMetric.total()).isGreaterThan(10);
metricMap.addSinceNanos("some", nanos);
visitor = new BasicMetricVisitor();
metricMap.visit(visitor);
timedMetric = visitor.timedMetrics().get(0);
assertThat(timedMetric.count()).isEqualTo(1);
assertThat(timedMetric.total()).isGreaterThan(10);
}
}
@@ -0,0 +1,55 @@
package io.ebeaninternal.server.profile;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class DTimedMetricTest {
@Test
public void addSinceNanos() throws InterruptedException {
DTimedMetric metric = new DTimedMetric("addSinceNanos");
long start = System.nanoTime();
Thread.sleep(11);
metric.addSinceNanos(start);
DTimeMetricStats stats = metric.collect(true);
assertThat(stats.count()).isEqualTo(1);
assertThat(stats.total()).isGreaterThan(10);
assertThat(stats.max()).isEqualTo(stats.total());
metric.addSinceNanos(start);
stats = metric.collect(true);
assertThat(stats.count()).isEqualTo(1);
assertThat(stats.total()).isGreaterThan(10);
assertThat(stats.max()).isEqualTo(stats.total());
}
@Test
public void addBatchSince() throws InterruptedException {
DTimedMetric metric = new DTimedMetric("addSinceNanos");
long start = System.nanoTime();
Thread.sleep(11);
metric.addBatchSince(start, 5);
DTimeMetricStats stats = metric.collect(true);
assertThat(stats.count()).isEqualTo(5);
assertThat(stats.total()).isGreaterThan(10000);
assertThat(stats.max()).isEqualTo(stats.total() / 5);
assertThat(stats.max()).isGreaterThan(10000 / 5);
metric.addBatchSince(start, 2);
stats = metric.collect(true);
assertThat(stats.count()).isEqualTo(2);
assertThat(stats.total()).isGreaterThan(10000);
assertThat(stats.max()).isEqualTo(stats.total() / 2);
}
}
@@ -0,0 +1,66 @@
package io.ebeaninternal.server.profile;
import io.ebean.meta.MetaTimedMetric;
import io.ebean.meta.SortMetric;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SortMetricTest {
private Comparator<MetaTimedMetric> sortMetric = SortMetric.NAME;
@Test
public void compare_list() {
List<DTimeMetricStats> list = new ArrayList<>();
list.add(create("d"));
list.add(create("b"));
list.add(create("c"));
list.add(create(null));
list.add(create("a"));
list.sort(sortMetric);
String names = list.stream().map(DTimeMetricStats::name).collect(Collectors.joining());
assertEquals("nullabcd", names);
}
@Test
public void compare_when_same() {
assertEquals(0, sortMetric.compare(create("foo"), create("foo")));
assertEquals(0, sortMetric.compare(create(null), create(null)));
}
@Test
public void compare_when_less() {
assertEquals(-1, sortMetric.compare(create("a"), create("b")));
assertEquals(-1, sortMetric.compare(create("foo"), create("goo")));
}
@Test
public void compare_when_more() {
assertEquals(1, sortMetric.compare(create("b"), create("a")));
assertEquals(1, sortMetric.compare(create("goo"), create("foo")));
}
@Test
public void compare_when_nulls() {
assertEquals(0, sortMetric.compare(create(null), create(null)));
assertEquals(1, sortMetric.compare(create("foo"), create(null)));
assertEquals(-1, sortMetric.compare(create(null), create("foo")));
}
private DTimeMetricStats create(String name) {
return new DTimeMetricStats(name, false, 0, 0, 0);
}
}
@@ -0,0 +1,21 @@
package io.ebeaninternal.server.profile;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class UtilLocationTest {
@Test
public void label() {
Assertions.assertThat(UtilLocation.label("foo")).isEqualTo("foo");
assertThat(UtilLocation.label("ProfileLocationTest$Other.<init>")).isEqualTo("ProfileLocationTest$Other.init");
}
@Test
public void loc() {
assertThat(UtilLocation.loc("org.foo.MyFoo.doIt(MyFoo.java:12)")).isEqualTo("org.foo.MyFoo.doIt");
assertThat(UtilLocation.label("org.foo.MyFoo.doIt")).isEqualTo("MyFoo.doIt");
}
}
@@ -0,0 +1,67 @@
package io.ebeaninternal.server.query;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DbOrderByTrimTest {
@Test
public void trim() {
String[] tests = {"foo", "bar", "a b c", "some_", "some()", "some'g'", "some('sd')", "some(a.b, '<s d>')"};
for (String value : tests) {
test(value, " desc");
}
for (String value : tests) {
test(value, " asc");
}
}
private void test(String value, String suffix) {
Assertions.assertEquals(value, DbOrderByTrim.trim(value + suffix));
}
@Test
public void test_when_pgp_sym_decrypt() {
assertEquals("pgp_sym_decrypt(t0.columnName, '<encryption key>')", DbOrderByTrim.trim("pgp_sym_decrypt(t0.columnName, '<encryption key>') desc"));
}
@Test
public void trim_doubleSpace() {
assertEquals("foo bar", DbOrderByTrim.trim("foo desc bar"));
}
@Test
public void trim_description() {
assertEquals("foo description", DbOrderByTrim.trim("foo description"));
assertEquals("foo ription", DbOrderByTrim.trim("foo desc ription"));
}
@Test
public void trim_asc1() {
assertEquals("foo asc1", DbOrderByTrim.trim("foo asc1"));
assertEquals("foo 1", DbOrderByTrim.trim("foo asc 1"));
}
@Test
public void trim_various() {
assertEquals("foo bar", DbOrderByTrim.trim("foo asc desc bar"));
assertEquals("foo bar", DbOrderByTrim.trim("foo desc asc desc asc asc bar"));
assertEquals("foo", DbOrderByTrim.trim("foo DESC"));
assertEquals("foo ", DbOrderByTrim.trim("foo DESC "));
assertEquals("foo", DbOrderByTrim.trim("foo ASC"));
assertEquals("foo ", DbOrderByTrim.trim("foo ASC "));
}
@Test
public void trim_nulls() {
assertEquals("foo", DbOrderByTrim.trim("foo nulls first asc"));
assertEquals("foo", DbOrderByTrim.trim("foo nulls last desc"));
assertEquals("foo", DbOrderByTrim.trim("foo asc nulls first"));
assertEquals("foo", DbOrderByTrim.trim("foo desc nulls last"));
}
}
@@ -0,0 +1,81 @@
package io.ebeaninternal.server.query;
import io.ebean.Version;
import org.junit.jupiter.api.Test;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class OrderVersionDescTest {
private final long now = System.currentTimeMillis();
@Test
public void sort() {
Version<?> atNull = atNull();
Version<?> at100 = at(100);
Version<?> at200 = at(200);
Version<?> at300 = at(300);
List<Version<?>> versions = new ArrayList<>();
versions.add(at200);
versions.add(atNull);
versions.add(at300);
versions.add(at100);
Collections.sort(versions, OrderVersionDesc.INSTANCE);
assertThat(versions.get(0)).isSameAs(at300);
assertThat(versions.get(1)).isSameAs(at200);
assertThat(versions.get(2)).isSameAs(at100);
assertThat(versions.get(3)).isSameAs(atNull);
}
@Test
public void compare_lt() {
assertEquals(OrderVersionDesc.INSTANCE.compare(at(0), at(1)), 1);
}
@Test
public void compare_gt() {
assertEquals(OrderVersionDesc.INSTANCE.compare(at(2), at(1)), -1);
}
@Test
public void compare_eq() {
assertEquals(OrderVersionDesc.INSTANCE.compare(at(1), at(1)), 0);
}
@Test
public void compare_nullFirst() {
assertEquals(OrderVersionDesc.INSTANCE.compare(atNull(), at(1)), 1);
}
@Test
public void compare_nullLast() {
assertEquals(OrderVersionDesc.INSTANCE.compare(at(0), atNull()), -1);
}
private Version<?> atNull() {
return new Version<>();
}
private Version<?> at(long diff) {
Timestamp timestamp = new Timestamp(now + diff);
Version<?> ver = new Version<>();
ver.setStart(timestamp);
return ver;
}
}
@@ -0,0 +1,50 @@
package io.ebeaninternal.server.query;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RawSqlQueryPlanKeyTest {
@Test
public void test_equals_same_instance() {
RawSqlQueryPlanKey key = key("select foo", true, "");
assertThat(key).isEqualTo(key);
assertThat(key.hashCode()).isEqualTo(key.hashCode());
}
@Test
public void test_equals_diff_instance() {
assertThat(key("select foo", true, "")).isEqualTo(key("select foo", true, ""));
assertThat(key("select foo", true, "").hashCode()).isEqualTo(key("select foo", true, "").hashCode());
}
@Test
public void test_notEquals_diff_sql() {
assertThat(key("select foo", true, "")).isNotEqualTo(key("select bar", true, ""));
assertThat(key("select foo", true, "").hashCode()).isNotEqualTo(key("select bar", true, "").hashCode());
}
@Test
public void test_notEquals_diff_rawSqlFlag() {
assertThat(key("select foo", true, "")).isNotEqualTo(key("select foo", false, ""));
assertThat(key("select foo", true, "").hashCode()).isNotEqualTo(key("select foo", false, "").hashCode());
}
@Test
public void test_notEquals_diff_logWhereSql() {
assertThat(key("select foo", true, "")).isNotEqualTo(key("select foo", true, "a"));
assertThat(key("select foo", true, "").hashCode()).isNotEqualTo(key("select foo", true, "a").hashCode());
}
private RawSqlQueryPlanKey key(String sql, boolean rawSql, String logWhereSql) {
return new RawSqlQueryPlanKey(sql, rawSql, logWhereSql);
}
}
@@ -0,0 +1,29 @@
package io.ebeaninternal.server.query;
import io.ebeaninternal.api.SpiQuery;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SqlTreeAliasTest {
@Test
public void parseRootAlias_when_rootAliasIsNull() {
SqlTreeAlias treeAlias = new SqlTreeAlias(null, SpiQuery.TemporalMode.CURRENT);
assertEquals("A B", treeAlias.parseRootAlias("${}A ${}B"));
assertEquals("ABC", treeAlias.parseRootAlias("A${}B${}C"));
}
@Test
public void parseRootAlias_when_rootAliasHasValue() {
SqlTreeAlias treeAlias = new SqlTreeAlias("t0", SpiQuery.TemporalMode.CURRENT);
assertEquals("t0.A t0.B", treeAlias.parseRootAlias("${}A ${}B"));
assertEquals("At0.Bt0.C", treeAlias.parseRootAlias("A${}B${}C"));
}
}
@@ -0,0 +1,65 @@
package io.ebeaninternal.server.query;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SqlTreeBuilderTest {
@Test
public void mergeOnDistinct_equal() {
Assertions.assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.id"), "t0.id");
}
@Test
public void mergeOnDistinct_add() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre"), "t0.cre, t0.id");
}
@Test
public void mergeOnDistinct_contained() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre, t0.id"), "t0.cre, t0.id");
}
@Test
public void mergeOnDistinct_overlap() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id, t1.id", "t0.cre, t0.id"), "t0.cre, t0.id, t1.id");
}
@Test
public void mergeOnDistinct_overlapBoth() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id, t1.id", "t0.cre, t1.id, t0.id"), "t0.cre, t1.id, t0.id");
}
@Test
public void mergeOnDistinct_inlineAscDesc() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre asc, t1.bb desc, t3.b"), "t0.cre, t1.bb, t3.b, t0.id");
}
@Test
public void mergeOnDistinct_inlineAscDesc2() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre desc, t1.bb asc, t3.b"), "t0.cre, t1.bb, t3.b, t0.id");
}
@Test
public void mergeOnDistinct_trailingAsc() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre asc"), "t0.cre, t0.id");
}
@Test
public void mergeOnDistinct_trailingDesc() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre desc"), "t0.cre, t0.id");
}
@Test
public void mergeOnDistinct_trailingDescNullsFirst() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre desc nulls first"), "t0.cre, t0.id");
}
@Test
public void mergeOnDistinct_trailingDescNullsLast() {
assertEquals(SqlTreeBuilder.mergeOnDistinct("t0.id", "t0.cre desc nulls last"), "t0.cre, t0.id");
}
}
@@ -0,0 +1,38 @@
package io.ebeaninternal.server.querydefn;
import io.ebeaninternal.api.BindValuesKey;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class BindValuesKeyTest {
@Test
public void update_with_null() {
BindValuesKey hash = new BindValuesKey();
hash.add(1).add(null).add("hello");
BindValuesKey hash2 = new BindValuesKey();
hash2.add(1).add(null).add("hello");
assertThat(hash).isEqualTo(hash2);
}
@Test
public void notEqual() {
BindValuesKey hash = new BindValuesKey();
hash.add(1).add(null).add("hello");
BindValuesKey hash2 = new BindValuesKey();
hash2.add(1).add("hello");
BindValuesKey hash3 = new BindValuesKey();
hash2.add(1).add(null);
assertThat(hash).isNotEqualTo(hash2);
assertThat(hash).isNotEqualTo(hash3);
assertThat(hash2).isNotEqualTo(hash3);
}
}
@@ -0,0 +1,109 @@
package io.ebeaninternal.server.querydefn;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.*;
public class OrmQueryDetailParserTest {
OrmQueryDetail parse(String query) {
return new OrmQueryDetailParser(query).parse();
}
@Test
public void parse_when_nullString() {
assertThrows(NullPointerException.class, () -> parse(null));
}
@Test
public void parse_when_emptyString() {
assertTrue(parse("").isEmpty());
}
@Test
public void testParseBasic() {
OrmQueryDetail detail = parse("select (id,name)");
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).containsExactly("id", "name");
}
@Test
public void testParseEmptySelect() {
OrmQueryDetail detail = parse("select fetch customer (email)");
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).isNull();
OrmQueryProperties chunk = detail.getChunk("customer", false);
assertThat(chunk.getPath()).isEqualTo("customer");
assertThat(chunk.getIncluded()).contains("email");
}
@Test
public void testParseSelectFetch() {
OrmQueryDetail detail = parse("select (id,name) fetch customer (email)");
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).contains("id", "name");
OrmQueryProperties chunk = detail.getChunk("customer", false);
assertThat(chunk.getPath()).isEqualTo("customer");
assertThat(chunk.getIncluded()).contains("email");
}
@Test
public void testParseSelectFetchMore() {
OrmQueryDetail detail = parse("select (id,name) fetch customer (email) fetch details.product (sku,description)");
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).contains("id", "name");
OrmQueryProperties chunk = detail.getChunk("customer", false);
assertThat(chunk.getPath()).isEqualTo("customer");
assertThat(chunk.getIncluded()).contains("email");
chunk = detail.getChunk("details.product", false);
assertThat(chunk.getPath()).isEqualTo("details.product");
assertThat(chunk.getIncluded()).contains("sku", "description");
}
@Test
public void testParseWithPlusQuery() {
OrmQueryDetail detail = parse("select (id,name) fetch customer (+query,id,name,email)");
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).contains("id", "name");
OrmQueryProperties chunk = detail.getChunk("customer", false);
assertThat(chunk.getPath()).isEqualTo("customer");
assertThat(chunk.getIncluded()).contains("id", "name", "email");
//FIXME: assertThat(chunk.isQueryFetch()).isTrue();
}
@Test
public void testTuneApply() {
OrmQueryDetail detail = parse("select (status) fetch customer (email)");
OrmQueryDetail tune = parse("select (id,name) fetch customer (+query,id,name,email)");
detail.tuneFetchProperties(tune);
OrmQueryProperties root = detail.getChunk(null, false);
assertNull(root.getPath());
assertThat(root.getIncluded()).contains("id", "name");
OrmQueryProperties chunk = detail.getChunk("customer", false);
assertThat(chunk.getPath()).isEqualTo("customer");
assertThat(chunk.getIncluded()).contains("id", "name", "email");
//FIXME: assertThat(chunk.isQueryFetch()).isTrue();
}
}
@@ -0,0 +1,63 @@
package io.ebeaninternal.server.querydefn;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class OrmQueryPropertiesParserTest {
@Test
public void when_null() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse(null);
assertAllDefaults(res);
assertThat(res.allProperties).isFalse();
assertThat(res.included).isNull();
}
@Test
public void when_empty() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse("");
assertAllDefaults(res);
assertThat(res.allProperties).isFalse();
assertThat(res.included).isNull();
}
@Test
public void when_hasStar() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse("*");
assertAllDefaults(res);
assertThat(res.allProperties).isTrue();
assertThat(res.included).isNull();
}
@Test
public void when_no_spaces() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse("id,name");
assertThat(res.allProperties).isFalse();
assertThat(res.included).containsExactly("id", "name");
}
@Test
public void when_spaced() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse("id, name");
assertThat(res.allProperties).isFalse();
assertThat(res.included).containsExactly("id", "name");
}
@Test
public void when_formula() {
OrmQueryPropertiesParser.Response res = OrmQueryPropertiesParser.parse("a,MD5(id::text) as b,c");
assertThat(res.allProperties).isFalse();
assertThat(res.included).containsExactly("a", "MD5(id::text) as b", "c");
}
private void assertAllDefaults(OrmQueryPropertiesParser.Response res) {
assertThat(res.included).isNull();
}
}
@@ -0,0 +1,84 @@
package io.ebeaninternal.server.querydefn;
import org.junit.jupiter.api.Test;
import java.util.LinkedHashSet;
import static org.assertj.core.api.Assertions.assertThat;
public class OrmQueryPropertiesTest {
String append(String prefix, OrmQueryProperties p1) {
StringBuilder sb = new StringBuilder();
p1.asStringDebug(prefix, sb);
return sb.toString();
}
@Test
public void construct_with_propertySet_when_empty() {
OrmQueryProperties p1 = new OrmQueryProperties(null, new LinkedHashSet<>());
assertThat(p1.allProperties()).isFalse();
assertThat(p1.getIncluded()).isEmpty();
}
@Test
public void construct_with_propertySet_when_one() {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("name");
OrmQueryProperties p1 = new OrmQueryProperties(null, set);
assertThat(p1.getIncluded()).containsOnly("name");
assertThat(p1.allProperties()).isFalse();
}
@Test
public void construct_with_propertySet_when_some() {
LinkedHashSet<String> set = new LinkedHashSet<>();
set.add("id");
set.add("name");
set.add("startDate");
OrmQueryProperties p1 = new OrmQueryProperties(null, set);
assertThat(p1.getIncluded()).containsOnly("id", "name", "startDate");
assertThat(p1.allProperties()).isFalse();
}
@Test
public void append_when_empty() {
OrmQueryProperties p1 = new OrmQueryProperties();
assertThat(append("select ", p1)).isEqualTo("select ");
}
@Test
public void append_when_someProperties() {
OrmQueryProperties p1 = new OrmQueryProperties(null, "id,name");
assertThat(append("select ", p1)).isEqualTo("select (id,name)");
}
@Test
public void append_when_somePropertiesWithOptions() {
OrmQueryProperties p1 = new OrmQueryProperties(null, "id,name,+cache");
//FIXME: assertThat(append("select ", p1)).isEqualTo("select (id,name,+cache)");
}
@Test
public void append_when_path_and_emptyProperties() {
OrmQueryProperties p1 = new OrmQueryProperties("customer", "");
assertThat(append("fetch ", p1)).isEqualTo("fetch customer ");
}
@Test
public void append_when_path_and_somePropertiesWithOptions() {
OrmQueryProperties p1 = new OrmQueryProperties("customer", "id,name,+cache");
//FIXME: assertThat(append("fetch ", p1)).isEqualTo("fetch customer (id,name,+cache)");
}
}
@@ -0,0 +1,15 @@
package io.ebeaninternal.server.querydefn;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class OrmUpdatePropertiesTest {
@Test
public void trim() {
Assertions.assertEquals("ship_id", OrmUpdateProperties.trim("${}ship_id"));
assertEquals("(ship_id)", OrmUpdateProperties.trim("(${}ship_id)"));
}
}
@@ -0,0 +1,65 @@
package io.ebeaninternal.server.rawsql;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.assertj.core.api.Assertions.assertThat;
public class ColumnMappingTest {
SpiRawSql.ColumnMapping.Column col(int indexPos, String dbColumn, String dbAlias) {
return new SpiRawSql.ColumnMapping.Column(indexPos, dbColumn, dbAlias);
}
SpiRawSql.ColumnMapping mapping(SpiRawSql.ColumnMapping.Column... cols) {
return new SpiRawSql.ColumnMapping(Arrays.asList(cols));
}
@Test
public void equals_same() {
SpiRawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
SpiRawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "name", null));
assertSame(mapping1, mapping2);
}
@Test
public void equals_diffPropertyName() {
SpiRawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
SpiRawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "diff", null));
assertDifferent(mapping1, mapping2);
}
@Test
public void equals_moreColumns() {
SpiRawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
SpiRawSql.ColumnMapping mapping2 = mapping(col(1, "id", null), col(2, "name", null), col(2, "diff", null));
assertDifferent(mapping1, mapping2);
}
@Test
public void equals_lessColumns() {
SpiRawSql.ColumnMapping mapping1 = mapping(col(1, "id", null), col(2, "name", null));
SpiRawSql.ColumnMapping mapping2 = mapping(col(1, "id", null));
assertDifferent(mapping1, mapping2);
}
private void assertSame(Object key, Object key1) {
assertThat(key).isEqualTo(key1);
assertThat(key.hashCode()).isEqualTo(key1.hashCode());
}
private void assertDifferent(Object key, Object key1) {
assertThat(key).isNotEqualTo(key1);
assertThat(key.hashCode()).isNotEqualTo(key1.hashCode());
}
}
@@ -0,0 +1,19 @@
package io.ebeaninternal.server.rawsql;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class DRawSqlServiceTest {
private final DRawSqlService dRawSqlService = new DRawSqlService();
@Test
public void combine() {
assertEquals("mycol", dRawSqlService.combine(null, null, "mycol"));
assertEquals("mytable.mycol", dRawSqlService.combine(null, "mytable", "mycol"));
assertEquals("myschema.mytable.mycol", dRawSqlService.combine("myschema", "mytable", "mycol"));
assertEquals("myschema.mycol", dRawSqlService.combine("myschema", null, "mycol"));
}
}
@@ -0,0 +1,75 @@
package io.ebeaninternal.server.rawsql;
import io.ebean.RawSql;
import io.ebean.RawSqlBuilder;
import io.ebeaninternal.server.rawsql.SpiRawSql;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class RawSqlKeyTest {
private SpiRawSql.Key key(String sqlStatement) {
return ((SpiRawSql) RawSqlBuilder.parse(sqlStatement).create()).getKey();
}
private SpiRawSql.Key key(RawSql rawSql) {
return ((SpiRawSql)rawSql).getKey();
}
@Test
public void equals_when_sameParsedSql() {
SpiRawSql.Key key = key("select id from customer");
SpiRawSql.Key key1 = key("select id from customer");
assertSame(key, key1);
}
@Test
public void equals_when_diffParsedSql() {
SpiRawSql.Key key = key("select id from customer");
SpiRawSql.Key key1 = key("select name from customer");
assertDifferent(key, key1);
}
@Test
public void equals_when_sameColumnMapping() {
SpiRawSql.Key key = key(RawSqlBuilder.parse("select id from customer").columnMapping("id", "b").create());
SpiRawSql.Key key1 = key(RawSqlBuilder.parse("select id from customer").columnMapping("id", "b").create());
assertSame(key, key1);
}
@Test
public void equals_when_diffColumnMapping() {
SpiRawSql.Key key = key(RawSqlBuilder.parse("select a from customer").columnMapping("a", "b").create());
SpiRawSql.Key key1 = key(RawSqlBuilder.parse("select a from customer").columnMapping("a", "c").create());
assertDifferent(key, key1);
}
@Test
public void equals_when_parseToUnpased() {
SpiRawSql.Key key = key(RawSqlBuilder.parse("select a from customer").columnMapping("a", "b").create());
SpiRawSql.Key key1 = key(RawSqlBuilder.unparsed("select a from customer").columnMapping("a", "c").create());
assertDifferent(key, key1);
}
private void assertSame(SpiRawSql.Key key, SpiRawSql.Key key1) {
assertThat(key).isEqualTo(key1);
assertThat(key.hashCode()).isEqualTo(key1.hashCode());
}
private void assertDifferent(SpiRawSql.Key key, SpiRawSql.Key key1) {
assertThat(key).isNotEqualTo(key1);
assertThat(key.hashCode()).isNotEqualTo(key1.hashCode());
}
}
@@ -0,0 +1,205 @@
package io.ebeaninternal.server.rawsql;
import io.ebeaninternal.server.rawsql.SpiRawSql.ColumnMapping;
import io.ebeaninternal.server.rawsql.SpiRawSql.ColumnMapping.Column;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class TestRawSqlColumnParsing {
@Test
public void testDeriveProperty() {
Assertions.assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName("item_total", "some_other")).isEqualTo("itemTotal");
assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName(null, "some_other")).isEqualTo("someOther");
assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName(null, "alias.some_other")).isEqualTo("someOther");
assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName(null, "alias.someOther")).isEqualTo("someOther");
assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName(null, "some")).isEqualTo("some");
assertThat(SpiRawSql.ColumnMapping.Column.derivePropertyName(null, "someOther")).isEqualTo("someOther");
}
@Test
public void test_simple() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a,b,c");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a", c.getPropertyName());
c = mapping.get("b");
assertEquals("b", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b", c.getPropertyName());
c = mapping.get("c");
assertEquals("c", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c", c.getPropertyName());
}
@Test
public void test_simpleWithSpacing() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse(" a , b , c ");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a", c.getPropertyName());
c = mapping.get("b");
assertEquals("b", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b", c.getPropertyName());
c = mapping.get("c");
assertEquals("c", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c", c.getPropertyName());
}
@Test
public void test_withAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, c c2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a0");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0", c.getPropertyName());
c = mapping.get("b1");
assertEquals("b", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1", c.getPropertyName());
c = mapping.get("c2");
assertEquals("c", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2", c.getPropertyName());
c = mapping.get("d3");
assertEquals("d", c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3", c.getPropertyName());
c = mapping.get("e4");
assertEquals("e", c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4", c.getPropertyName());
}
@Test
public void test_withDatabaseFunction() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a a0,b b1, MONTH(MAKEDATE(2015, 241)) m2 , d d3 , e e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a0");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0", c.getPropertyName());
c = mapping.get("b1");
assertEquals("b", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1", c.getPropertyName());
c = mapping.get("m2");
assertEquals("MONTH(MAKEDATE(2015, 241))", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("m2", c.getPropertyName());
c = mapping.get("d3");
assertEquals("d", c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3", c.getPropertyName());
c = mapping.get("e4");
assertEquals("e", c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4", c.getPropertyName());
}
@Test
public void test_withAsAlias() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a as a0,'b' b1, \"c(blah)\" as c2 , d as d3 , e as e4 ");
Map<String, Column> mapping = columnMapping.mapping();
assertEquals(5, mapping.size());
Column c = mapping.get("a0");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a0", c.getPropertyName());
c = mapping.get("b1");
assertEquals("'b'", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b1", c.getPropertyName());
c = mapping.get("c2");
assertEquals("\"c(blah)\"", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c2", c.getPropertyName());
c = mapping.get("d3");
assertEquals("d", c.getDbColumn());
assertEquals(3, c.getIndexPos());
assertEquals("d3", c.getPropertyName());
c = mapping.get("e4");
assertEquals("e", c.getDbColumn());
assertEquals(4, c.getIndexPos());
assertEquals("e4", c.getPropertyName());
}
@Test
public void test_doubleColon() {
ColumnMapping columnMapping = DRawSqlColumnsParser.parse("a,MD5(id::text) as b,c");
Map<String, Column> mapping = columnMapping.mapping();
Column c = mapping.get("a");
assertEquals("a", c.getDbColumn());
assertEquals(0, c.getIndexPos());
assertEquals("a", c.getPropertyName());
c = mapping.get("b");
assertEquals("MD5(id::text)", c.getDbColumn());
assertEquals(1, c.getIndexPos());
assertEquals("b", c.getPropertyName());
c = mapping.get("c");
assertEquals("c", c.getDbColumn());
assertEquals(2, c.getIndexPos());
assertEquals("c", c.getPropertyName());
}
}
@@ -0,0 +1,149 @@
package io.ebeaninternal.server.rawsql;
import io.ebean.SqlRow;
import io.ebeaninternal.server.rawsql.DRawSqlService;
import org.junit.jupiter.api.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class TestRawSqlService {
@Test
public void testDistinctColumnNames() throws SQLException {
ResultSetMetaData rsetmeta = mock(ResultSetMetaData.class);
ResultSet rset = mock(ResultSet.class);
when(rsetmeta.getColumnCount()).thenReturn(3);
when(rset.getMetaData()).thenReturn(rsetmeta);
for (int i = 1; i < 4; i++) {
when(rsetmeta.getColumnLabel(i)).thenReturn(null);
when(rsetmeta.getColumnName(i)).thenReturn("col" + i);
when(rsetmeta.getSchemaName(i)).thenReturn("schema" + i);
when(rsetmeta.getTableName(i)).thenReturn("table" + i);
when(rset.getObject(i)).thenReturn("dat1_" + i).thenReturn("dat2_" + i);
}
DRawSqlService service = new DRawSqlService();
SqlRow result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("col1", "col2", "col3");
for (int i = 1; i < 4; i++) {
assertThat(result.get("col" + i)).isEqualTo("dat1_" + i);
}
result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("col1", "col2", "col3");
for (int i = 1; i < 4; i++) {
assertThat(result.get("col" + i)).isEqualTo("dat2_" + i);
}
}
@Test
public void testDistinctColumnLabels() throws SQLException {
ResultSetMetaData rsetmeta = mock(ResultSetMetaData.class);
ResultSet rset = mock(ResultSet.class);
when(rsetmeta.getColumnCount()).thenReturn(3);
when(rset.getMetaData()).thenReturn(rsetmeta);
for (int i = 1; i < 4; i++) {
when(rsetmeta.getColumnLabel(i)).thenReturn("label" + i);
when(rsetmeta.getColumnName(i)).thenReturn("col" + i);
when(rsetmeta.getSchemaName(i)).thenReturn("schema" + i);
when(rsetmeta.getTableName(i)).thenReturn("table" + i);
when(rset.getObject(i)).thenReturn("dat1_" + i).thenReturn("dat2_" + i);
}
DRawSqlService service = new DRawSqlService();
SqlRow result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("label1", "label2", "label3");
for (int i = 1; i < 4; i++) {
assertThat(result.get("label" + i)).isEqualTo("dat1_" + i);
}
result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("label1", "label2", "label3");
for (int i = 1; i < 4; i++) {
assertThat(result.get("label" + i)).isEqualTo("dat2_" + i);
}
}
@Test
public void testIdenticalColumnNames() throws SQLException {
ResultSetMetaData rsetmeta = mock(ResultSetMetaData.class);
ResultSet rset = mock(ResultSet.class);
when(rsetmeta.getColumnCount()).thenReturn(3);
when(rset.getMetaData()).thenReturn(rsetmeta);
for (int i = 1; i < 4; i++) {
when(rsetmeta.getColumnLabel(i)).thenReturn(null);
when(rsetmeta.getColumnName(i)).thenReturn("col");
when(rsetmeta.getSchemaName(i)).thenReturn("schema" + i);
when(rsetmeta.getTableName(i)).thenReturn("table" + i);
when(rset.getObject(i)).thenReturn("dat1_" + i).thenReturn("dat2_" + i);
}
DRawSqlService service = new DRawSqlService();
SqlRow result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("col", "schema2.table2.col", "schema3.table3.col");
assertThat(result.get("col")).isEqualTo("dat1_1");
assertThat(result.get("schema2.table2.col")).isEqualTo("dat1_2");
assertThat(result.get("schema3.table3.col")).isEqualTo("dat1_3");
result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("col", "schema2.table2.col", "schema3.table3.col");
assertThat(result.get("col")).isEqualTo("dat2_1");
assertThat(result.get("schema2.table2.col")).isEqualTo("dat2_2");
assertThat(result.get("schema3.table3.col")).isEqualTo("dat2_3");
}
@Test
public void testIdenticalColumnLabels() throws SQLException {
ResultSetMetaData rsetmeta = mock(ResultSetMetaData.class);
ResultSet rset = mock(ResultSet.class);
when(rsetmeta.getColumnCount()).thenReturn(3);
when(rset.getMetaData()).thenReturn(rsetmeta);
for (int i = 1; i < 4; i++) {
when(rsetmeta.getColumnLabel(i)).thenReturn("label");
when(rsetmeta.getColumnName(i)).thenReturn("col");
when(rsetmeta.getSchemaName(i)).thenReturn("schema" + i);
when(rsetmeta.getTableName(i)).thenReturn("table" + i);
when(rset.getObject(i)).thenReturn("dat1_" + i).thenReturn("dat2_" + i);
}
DRawSqlService service = new DRawSqlService();
SqlRow result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("label", "schema2.table2.label", "schema3.table3.label");
assertThat(result.get("label")).isEqualTo("dat1_1");
assertThat(result.get("schema2.table2.label")).isEqualTo("dat1_2");
assertThat(result.get("schema3.table3.label")).isEqualTo("dat1_3");
result = service.sqlRow(rset, "1", false);
assertThat(result.keySet()).contains("label", "schema2.table2.label", "schema3.table3.label");
assertThat(result.get("label")).isEqualTo("dat2_1");
assertThat(result.get("schema2.table2.label")).isEqualTo("dat2_2");
assertThat(result.get("schema3.table3.label")).isEqualTo("dat2_3");
}
}
@@ -0,0 +1,47 @@
package io.ebeaninternal.server.transaction;
import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class TableModStateTest {
private TableModState tableModState = new TableModState();
@Test
public void isValid() {
long before = System.nanoTime();
tableModState.touch(setOf("one", "two", "three"));
long after = System.nanoTime();
// empty
assertTrue(tableModState.isValid(Collections.emptySet(), 12L));
// no entry
assertTrue(tableModState.isValid(setOf("noEntry"), 12L));
// later timestamp
assertTrue(tableModState.isValid(setOf("one"), after));
assertTrue(tableModState.isValid(setOf("one", "two", "noEntry"), after));
// invalid
assertFalse(tableModState.isValid(setOf("one"), before));
assertFalse(tableModState.isValid(setOf("one", "two"), before));
assertFalse(tableModState.isValid(setOf("three", "two"), before));
}
private Set<String> setOf(String... tables) {
Set<String> touched = new HashSet<>();
Collections.addAll(touched, tables);
return touched;
}
}
@@ -0,0 +1,93 @@
package io.ebeaninternal.server.util;
import org.junit.jupiter.api.Test;
import java.util.EmptyStackException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class ArrayStackTest {
@Test
public void testPushPop() {
ArrayStack<String> stack = new ArrayStack<>();
stack.push("1");
stack.push("2");
stack.push("3");
assertThat(stack.pop()).isEqualTo("3");
assertThat(stack.pop()).isEqualTo("2");
assertThat(stack.pop()).isEqualTo("1");
}
@Test
public void testPushPop_given_stackInitialSizeExceeded() {
ArrayStack<String> stack = new ArrayStack<>(2);
stack.push("1");
stack.push("2");
stack.push("3");
assertThat(stack.pop()).isEqualTo("3");
assertThat(stack.pop()).isEqualTo("2");
assertThat(stack.pop()).isEqualTo("1");
}
@Test
public void testPop_given_emptyStack_throws() {
ArrayStack<String> stack = new ArrayStack<>();
assertThrows(EmptyStackException.class, stack::pop);
}
@Test
public void testPeek_given_empty_throws() {
ArrayStack<String> stack = new ArrayStack<>();
assertThrows(EmptyStackException.class, stack::peek);
}
@Test
public void testPeek_given_notEmpty() {
ArrayStack<String> stack = new ArrayStack<>();
stack.push("1");
assertThat(stack.peek()).isEqualTo("1");
}
@Test
public void testPeekWithNull() {
ArrayStack<String> stack = new ArrayStack<>();
assertThat(stack.peekWithNull()).isNull();
stack.push("1");
assertThat(stack.peekWithNull()).isEqualTo("1");
}
@Test
public void testIsEmpty() {
ArrayStack<String> stack = new ArrayStack<>();
assertThat(stack.isEmpty()).isTrue();
stack.push("1");
assertThat(stack.isEmpty()).isFalse();
}
@Test
public void testSize() {
ArrayStack<String> stack = new ArrayStack<>();
assertThat(stack.size()).isEqualTo(0);
stack.push("1");
assertThat(stack.size()).isEqualTo(1);
stack.push("w");
assertThat(stack.size()).isEqualTo(2);
}
@Test
public void testContains() {
ArrayStack<String> stack = new ArrayStack<>();
stack.push("1");
assertThat(stack.contains("1")).isTrue();
assertThat(stack.contains("2")).isFalse();
}
}
@@ -0,0 +1,50 @@
package io.ebeaninternal.server.util;
import io.ebeaninternal.api.BindParams;
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class BindParamsParserTest {
@Test
public void testParse() throws Exception {
String dml = "delete from foo where id in (:ids)";
BindParams bindParams = new BindParams();
bindParams.setParameter("ids", Arrays.asList("1", "2", "3"));
String sql1 = BindParamsParser.parse(bindParams, dml);
assertEquals("delete from foo where id in (?,?,?)", sql1);
bindParams.setParameter("ids", Arrays.asList("451", "52"));
sql1 = BindParamsParser.parse(bindParams, dml);
assertEquals("delete from foo where id in (?,?)", sql1);
bindParams.setParameter("ids", Arrays.asList("545", "656"));
sql1 = BindParamsParser.parse(bindParams, dml);
assertEquals("delete from foo where id in (?,?)", sql1);
bindParams.setParameter("ids", Arrays.asList("545df", "df656", "SDF", "sdf"));
sql1 = BindParamsParser.parse(bindParams, dml);
assertEquals("delete from foo where id in (?,?,?,?)", sql1);
}
@Test
public void findNameStart() {
assertEquals(5, BindParamsParser.findNameStart("some :name = ?", 0));
}
@Test
public void findNameStart_doubleColon() {
assertEquals(-1, BindParamsParser.findNameStart("some ::name = ?", 0));
}
@Test
public void findNameStart_doubleColonSkip() {
assertEquals(10, BindParamsParser.findNameStart("some ::na :a = ?", 0));
}
}
@@ -0,0 +1,23 @@
package io.ebeaninternal.server.util;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
public class ChecksumTest {
@Test
public void checksum() {
final long val = Checksum.checksum("Hello world");
assertThat(val).isEqualTo(2346098258L);
assertThat(Checksum.checksum("Hello world")).isEqualTo(val);
assertThat(Checksum.checksum("hello world")).isNotEqualTo(val);
}
@Test
public void checksum_shortString() {
final long val0 = Checksum.checksum("2012-01-11");
final long val1 = Checksum.checksum("2012-10-02");
assertThat(val0).isNotEqualTo(val1);
}
}
@@ -0,0 +1,60 @@
package io.ebeaninternal.server.util;
import org.junit.jupiter.api.Test;
import java.util.Set;
import static org.assertj.core.api.Assertions.assertThat;
public class DSelectColumnsParserTest {
@Test
public void parse() {
Set<String> cols = DSelectColumnsParser.parse("a,MD5(id::text) as b,c");
assertThat(cols).containsExactly("a", "MD5(id::text) as b", "c");
}
@Test
public void whitespace_is_trimmed() {
Set<String> cols = DSelectColumnsParser.parse("a , MD5(id::text) as b , c ");
assertThat(cols).containsExactly("a", "MD5(id::text) as b", "c");
}
@Test
public void nestedFunctions() {
Set<String> cols = DSelectColumnsParser.parse("a , concat(id,'sd',inner(foo)) as b , c ");
assertThat(cols).containsExactly("a", "concat(id,'sd',inner(foo)) as b", "c");
}
@Test
public void basic() {
Set<String> cols = DSelectColumnsParser.parse("name , status , billingAddress ");
assertThat(cols).containsExactly("name", "status", "billingAddress");
}
@Test
public void basic_noWhitespace() {
Set<String> cols = DSelectColumnsParser.parse("a,b,c");
assertThat(cols).containsExactly("a", "b", "c");
}
@Test
public void formula_noWhitespace() {
Set<String> cols = DSelectColumnsParser.parse("a,concat(x,y),c");
assertThat(cols).containsExactly("a", "concat(x,y)", "c");
}
@Test
public void with_logicalCast_andAsAlias() {
Set<String> cols = DSelectColumnsParser.parse("name , concat(status,'-end')::String as fullName , billingAddress ");
assertThat(cols).containsExactly("name", "concat(status,'-end')::String as fullName", "billingAddress");
}
}
@@ -0,0 +1,53 @@
package io.ebeaninternal.server.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
public class Md5Test {
@Test
public void hash() throws Exception {
String content = "some random content we wish to hash";
String hash1 = Md5.hash(content);
String hash2 = Md5.hash(content);
assertEquals(hash1, hash2);
assertEquals(hash1, "62c20bf679ff56cb746452ab5c88e3ed");
}
@Test
public void hashDifferent() throws Exception {
String hash1 = Md5.hash("one");
String hash2 = Md5.hash("two");
String hash3 = Md5.hash("onetwo");
assertNotEquals(hash1, hash2);
assertNotEquals(hash2, hash3);
assertEquals(hash1, "f97c5d29941bfb1b2fdab0874906ab82");
}
@Test
public void hashMulti() {
String hash1 = Md5.hash("one", "two");
String hash2 = Md5.hash("onetwo");
assertEquals(hash1, hash2);
assertEquals(hash1, "5b9164ad6f496d9dee12ec7634ce253f");
}
@Test
public void hashMulti_when_null() {
String hash1 = Md5.hash("one", null);
String hash2 = Md5.hash("one");
assertEquals(hash1, hash2);
assertEquals(hash1, "f97c5d29941bfb1b2fdab0874906ab82");
}
@Test
public void when_null() {
String hash1 = Md5.hash(null, null);
assertEquals(hash1, "d41d8cd98f00b204e9800998ecf8427e");
}
}
@@ -0,0 +1,4 @@
package org.tests.model.basic;
public class Contact {
}
@@ -0,0 +1,4 @@
package org.tests.model.basic;
public class Customer {
}