33 | * A fresh database instance will be created for each test method.
34 | *
35 | *
36 | * Note that this class is meant to be used for DDL operations only. Any attempt to run DML operations may result in
37 | * errors.
38 | *
39 | */
40 | public class HiveServer2JUnitRule extends BeejuJUnitRule {
41 |
42 | private HiveServer2Core hiveServer2Core = new HiveServer2Core(core);
43 |
44 | /**
45 | * Create a HiveServer2 service with a pre-created database "test_database".
46 | */
47 | public HiveServer2JUnitRule() {
48 | this("test_database");
49 | }
50 |
51 | /**
52 | * Create a HiveServer2 service with a pre-created database using the provided name.
53 | *
54 | * @param databaseName Database name.
55 | */
56 | public HiveServer2JUnitRule(String databaseName) {
57 | this(databaseName, null);
58 | }
59 |
60 | /**
61 | * Create a HiveServer2 service with a pre-created database using the provided name and configuration.
62 | *
63 | * @param databaseName Database name.
64 | * @param configuration Hive configuration properties.
65 | */
66 | public HiveServer2JUnitRule(String databaseName, Map configuration) {
67 | super(databaseName, configuration);
68 | }
69 |
70 | @Override
71 | public void starting(Description description) {
72 | System.clearProperty(CONNECT_URL_KEY.getVarname());
73 | try {
74 | hiveServer2Core.startServerSocket();
75 | } catch (IOException e) {
76 | throw new UncheckedIOException("Error starting HiveServer2 server socket", e);
77 | }
78 | super.starting(description);
79 | try {
80 | hiveServer2Core.initialise();
81 | } catch (InterruptedException e) {
82 | throw new RuntimeException("Error initialising HiveServer2 core", e);
83 | }
84 | }
85 |
86 | @Override
87 | public void finished(Description description) {
88 | try {
89 | hiveServer2Core.shutdown();
90 | } finally {
91 | super.finished(description);
92 | }
93 | }
94 |
95 | /**
96 | * @return the name of the Hive JDBC driver class used to access the database.
97 | */
98 | @Override
99 | public String driverClassName() {
100 | return HiveDriver.class.getName();
101 | }
102 |
103 | /**
104 | * @return {@link com.hotels.beeju.core.HiveServer2Core#getJdbcConnectionUrl()}.
105 | */
106 | @Override
107 | public String connectionURL() {
108 | return hiveServer2Core.getJdbcConnectionUrl();
109 | }
110 |
111 | }
112 |
--------------------------------------------------------------------------------
/src/main/java/com/hotels/beeju/HiveMetaStoreJUnitRule.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju;
17 |
18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY;
19 |
20 | import java.util.Map;
21 | import java.util.concurrent.ExecutionException;
22 |
23 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
24 | import org.junit.runner.Description;
25 | import org.slf4j.Logger;
26 | import org.slf4j.LoggerFactory;
27 |
28 | import com.hotels.beeju.core.HiveMetaStoreCore;
29 |
30 | /**
31 | * A JUnit {@link org.junit.Rule} that creates a Hive Metastore backed by an in-memory database.
32 | *
33 | * A fresh database instance will be created for each test method.
34 | */
35 | public class HiveMetaStoreJUnitRule extends BeejuJUnitRule {
36 |
37 | private static final Logger log = LoggerFactory.getLogger(HiveMetaStoreJUnitRule.class);
38 |
39 | private final HiveMetaStoreCore hiveMetaStoreCore = new HiveMetaStoreCore(core);
40 |
41 | /**
42 | * Create a Hive Metastore with a pre-created database "test_database".
43 | */
44 | public HiveMetaStoreJUnitRule() {
45 | this("test_database");
46 | }
47 |
48 | /**
49 | * Create a Hive Metastore with a pre-created database using the provided name.
50 | *
51 | * @param databaseName Database name.
52 | */
53 | public HiveMetaStoreJUnitRule(String databaseName) {
54 | this(databaseName, null);
55 | }
56 |
57 | /**
58 | * Create a Hive Metastore with a pre-created database using the provided name and configuration.
59 | *
60 | * @param databaseName Database name.
61 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these
62 | * with its defaults.
63 | */
64 | public HiveMetaStoreJUnitRule(String databaseName, Map preConfiguration) {
65 | super(databaseName, preConfiguration);
66 | }
67 |
68 | /**
69 | * Create a Hive Metastore with a pre-created database using the provided name and configuration.
70 | *
71 | * @param databaseName Database name.
72 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these
73 | * with its defaults.
74 | * @param postConfiguration Hive configuration properties that will be set to override BeeJU's defaults.
75 | */
76 | public HiveMetaStoreJUnitRule(
77 | String databaseName,
78 | Map preConfiguration,
79 | Map postConfiguration) {
80 | super(databaseName, preConfiguration, postConfiguration);
81 | }
82 |
83 | @Override
84 | public void starting(Description description) {
85 | System.clearProperty(CONNECT_URL_KEY.getVarname());
86 | super.starting(description);
87 | try {
88 | hiveMetaStoreCore.initialise();
89 | } catch (InterruptedException | ExecutionException e) {
90 | throw new RuntimeException("Error initialising metastore core", e);
91 | }
92 | }
93 |
94 | @Override
95 | public void finished(Description description) {
96 | try {
97 | hiveMetaStoreCore.shutdown();
98 | } catch (Throwable t) {
99 | log.warn("Error shutting down metastore core", t);
100 | }
101 | super.finished(description);
102 | }
103 |
104 | /**
105 | * @return the {@link com.hotels.beeju.core.HiveMetaStoreCore#client()}.
106 | */
107 | public HiveMetaStoreClient client() {
108 | return hiveMetaStoreCore.client();
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/src/main/java/com/hotels/beeju/core/ThriftHiveMetaStoreCore.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju.core;
17 |
18 | import java.net.ServerSocket;
19 | import java.util.concurrent.ExecutorService;
20 | import java.util.concurrent.Executors;
21 | import java.util.concurrent.TimeUnit;
22 | import java.util.concurrent.atomic.AtomicBoolean;
23 | import java.util.concurrent.locks.Condition;
24 | import java.util.concurrent.locks.Lock;
25 | import java.util.concurrent.locks.ReentrantLock;
26 |
27 | import org.apache.hadoop.hive.conf.HiveConf;
28 | import org.apache.hadoop.hive.metastore.HiveMetaStore;
29 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
30 | import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge;
31 | import org.apache.hadoop.hive.metastore.security.HadoopThriftAuthBridge23;
32 | import org.slf4j.Logger;
33 | import org.slf4j.LoggerFactory;
34 |
35 | public class ThriftHiveMetaStoreCore {
36 |
37 | private static final Logger LOG = LoggerFactory.getLogger(ThriftHiveMetaStoreCore.class);
38 | private final ExecutorService thriftServer;
39 | private final BeejuCore beejuCore;
40 | private int thriftPort = -1;
41 |
42 | public ThriftHiveMetaStoreCore(BeejuCore beejuCore) {
43 | this.beejuCore = beejuCore;
44 | thriftServer = Executors.newSingleThreadExecutor();
45 | }
46 |
47 | public void initialise() throws Exception {
48 | final Lock startLock = new ReentrantLock();
49 | final Condition startCondition = startLock.newCondition();
50 | final AtomicBoolean startedServing = new AtomicBoolean();
51 | int socketPort = 0;
52 | if (thriftPort > 0) {
53 | socketPort = thriftPort;
54 | }
55 | try (ServerSocket socket = new ServerSocket(socketPort)) {
56 | thriftPort = socket.getLocalPort();
57 | }
58 | beejuCore.setHiveVar(HiveConf.ConfVars.METASTOREURIS, getThriftConnectionUri());
59 | final HiveConf hiveConf = new HiveConf(beejuCore.conf(), HiveMetaStoreClient.class);
60 | thriftServer.execute(() -> {
61 | try {
62 | HadoopThriftAuthBridge bridge = HadoopThriftAuthBridge23.getBridge();
63 | HiveMetaStore.startMetaStore(thriftPort, bridge, hiveConf, startLock, startCondition, startedServing);
64 | } catch (Throwable e) {
65 | LOG.error("Unable to start a Thrift server for Hive Metastore", e);
66 | }
67 | });
68 | int i = 0;
69 | while (i++ < 3) {
70 | startLock.lock();
71 | try {
72 | if (startCondition.await(1, TimeUnit.MINUTES)) {
73 | break;
74 | }
75 | } finally {
76 | startLock.unlock();
77 | }
78 | if (i == 3) {
79 | throw new RuntimeException("Maximum number of tries reached whilst waiting for Thrift server to be ready");
80 | }
81 | }
82 | }
83 |
84 | public void shutdown() {
85 | thriftServer.shutdown();
86 | }
87 |
88 | /**
89 | * @return The Thrift connection string for the Metastore service.
90 | */
91 | public String getThriftConnectionUri() {
92 | return "thrift://localhost:" + thriftPort;
93 | }
94 |
95 | /**
96 | * @return The port used for the Thrift Metastore service.
97 | */
98 | public int getThriftPort() {
99 | return thriftPort;
100 | }
101 |
102 | /**
103 | * @param thriftPort The Port to use for the Thrift Hive metastore, if not set then a port number will automatically be allocated.
104 | */
105 | public void setThriftPort(int thriftPort) {
106 | if (thriftPort < 0) {
107 | throw new IllegalArgumentException("Thrift port must be >=0, not " + thriftPort);
108 | }
109 | this.thriftPort = thriftPort;
110 | }
111 |
112 | public String getDatabaseName(){
113 | return beejuCore.databaseName();
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/main/java/com/hotels/beeju/ThriftHiveMetaStoreJUnitRule.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju;
17 |
18 | import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.CONNECT_URL_KEY;
19 |
20 | import java.util.Map;
21 |
22 | import org.junit.runner.Description;
23 |
24 | import com.hotels.beeju.core.ThriftHiveMetaStoreCore;
25 |
26 | /**
27 | * A JUnit Rule that creates a Hive Metastore Thrift service backed by a Hive Metastore using an HSQLDB in-memory
28 | * database.
29 | *
30 | * A fresh database instance will be created for each test method.
31 | *
32 | */
33 | public class ThriftHiveMetaStoreJUnitRule extends HiveMetaStoreJUnitRule {
34 |
35 | private ThriftHiveMetaStoreCore thriftHiveMetaStoreCore = new ThriftHiveMetaStoreCore(core);
36 |
37 | /**
38 | * Create a Thrift Hive Metastore service with a pre-created database "test_database".
39 | */
40 | public ThriftHiveMetaStoreJUnitRule() {
41 | this("test_database");
42 | }
43 |
44 | /**
45 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name.
46 | *
47 | * @param databaseName Database name.
48 | */
49 | public ThriftHiveMetaStoreJUnitRule(String databaseName) {
50 | this(databaseName, null);
51 | }
52 |
53 | /**
54 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name and configuration.
55 | *
56 | * @param databaseName Database name.
57 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these
58 | * with its defaults.
59 | */
60 | public ThriftHiveMetaStoreJUnitRule(String databaseName, Map preConfiguration) {
61 | super(databaseName, preConfiguration);
62 | }
63 |
64 | /**
65 | * Create a Thrift Hive Metastore service with a pre-created database using the provided name and configuration.
66 | *
67 | * @param databaseName Database name.
68 | * @param preConfiguration Hive configuration properties that will be set prior to BeeJU potentially overriding these
69 | * with its defaults.
70 | * @param postConfiguration Hive configuration properties that will be set to override BeeJU's defaults.
71 | */
72 | public ThriftHiveMetaStoreJUnitRule(
73 | String databaseName,
74 | Map preConfiguration,
75 | Map postConfiguration) {
76 | super(databaseName, preConfiguration, postConfiguration);
77 | }
78 |
79 | @Override
80 | public void starting(Description description) {
81 | System.clearProperty(CONNECT_URL_KEY.getVarname());
82 | try {
83 | thriftHiveMetaStoreCore.initialise();
84 | } catch (Exception e) {
85 | throw new RuntimeException(e);
86 | }
87 | super.starting(description);
88 | }
89 |
90 | @Override
91 | public void finished(Description description) {
92 | try {
93 | thriftHiveMetaStoreCore.shutdown();
94 | } finally {
95 | super.finished(description);
96 | }
97 | }
98 |
99 | /**
100 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftConnectionUri()}.
101 | */
102 | public String getThriftConnectionUri() {
103 | return thriftHiveMetaStoreCore.getThriftConnectionUri();
104 | }
105 |
106 | /**
107 | * @return {@link com.hotels.beeju.core.ThriftHiveMetaStoreCore#getThriftPort()}
108 | */
109 | public int getThriftPort() {
110 | return thriftHiveMetaStoreCore.getThriftPort();
111 | }
112 |
113 | /**
114 | * @param thriftPort The Port to use for the Thrift Hive metastore, if not set then a port number will automatically
115 | * be allocated.
116 | */
117 | public void setThriftPort(int thriftPort) {
118 | thriftHiveMetaStoreCore.setThriftPort(thriftPort);
119 | }
120 |
121 | }
122 |
--------------------------------------------------------------------------------
/src/test/java/com/hotels/beeju/extensions/ThriftHiveMetaStoreJUnitExtensionTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju.extensions;
17 |
18 | import static org.hamcrest.CoreMatchers.is;
19 | import static org.hamcrest.MatcherAssert.assertThat;
20 | import static org.junit.jupiter.api.Assertions.assertThrows;
21 |
22 | import java.io.File;
23 | import java.util.Collections;
24 | import java.util.List;
25 | import java.util.Map;
26 |
27 | import org.apache.hadoop.hive.conf.HiveConf;
28 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
29 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
30 | import org.apache.hadoop.hive.metastore.api.Database;
31 | import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
32 | import org.junit.jupiter.api.Test;
33 | import org.junit.jupiter.api.extension.RegisterExtension;
34 |
35 | public class ThriftHiveMetaStoreJUnitExtensionTest {
36 |
37 | @RegisterExtension
38 | ThriftHiveMetaStoreJUnitExtension defaultDbExtension = new ThriftHiveMetaStoreJUnitExtension();
39 |
40 | @RegisterExtension
41 | ThriftHiveMetaStoreJUnitExtension customDbExtension = new ThriftHiveMetaStoreJUnitExtension("my_test_database");
42 |
43 | @RegisterExtension
44 | ThriftHiveMetaStoreJUnitExtension customPropertiesExtension = new ThriftHiveMetaStoreJUnitExtension(
45 | "custom_props_database", customConfProperties());
46 |
47 | private void assertExtensionInitialised(ThriftHiveMetaStoreJUnitExtension hive) throws Exception {
48 | String databaseName = hive.databaseName();
49 |
50 | Database database = hive.client().getDatabase(databaseName);
51 |
52 | assertThat(database.getName(), is(databaseName));
53 | File databaseFolder = new File(hive.getWarehouseDirectory(), databaseName);
54 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString()));
55 |
56 | assertThat(hive.getThriftConnectionUri(), is("thrift://localhost:" + hive.getThriftPort()));
57 | HiveConf conf = new HiveConf(hive.conf());
58 | conf.setVar(HiveConf.ConfVars.METASTOREURIS, hive.getThriftConnectionUri());
59 | HiveMetaStoreClient client = new HiveMetaStoreClient(conf);
60 | try {
61 | List databases = client.getAllDatabases();
62 | assertThat(databases.size(), is(2));
63 | assertThat(databases.get(0), is("default"));
64 | assertThat(databases.get(1), is(databaseName));
65 | } finally {
66 | client.close();
67 | }
68 | }
69 |
70 | private Map customConfProperties() {
71 | return Collections.singletonMap("my.custom.key", "my.custom.value");
72 | }
73 |
74 | @Test
75 | public void hiveDefaultName() throws Exception {
76 | assertExtensionInitialised(defaultDbExtension);
77 | }
78 |
79 | @Test
80 | public void hiveCustomName() throws Exception {
81 | assertExtensionInitialised(customDbExtension);
82 | }
83 |
84 | @Test
85 | public void customProperties() {
86 | HiveConf hiveConf = customPropertiesExtension.conf();
87 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value"));
88 | }
89 |
90 | @Test
91 | public void createExistingDatabase() {
92 | assertThrows(AlreadyExistsException.class,
93 | () -> defaultDbExtension.createDatabase(defaultDbExtension.databaseName()));
94 | }
95 |
96 | @Test
97 | public void createDatabaseNullName() {
98 | assertThrows(NullPointerException.class, () -> defaultDbExtension.createDatabase(null));
99 | }
100 |
101 | @Test
102 | public void createDatabaseInvalidName() {
103 | assertThrows(InvalidObjectException.class, () -> defaultDbExtension.createDatabase(""));
104 | }
105 |
106 | @Test
107 | public void thriftPort() {
108 | int thriftPort = 3333;
109 | defaultDbExtension.setThriftPort(thriftPort);
110 | assertThat(defaultDbExtension.getThriftPort(), is(thriftPort));
111 | }
112 | }
113 |
--------------------------------------------------------------------------------
/src/test/java/com/hotels/beeju/ThriftHiveMetaStoreJUnitRuleTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju;
17 |
18 | import static org.hamcrest.CoreMatchers.is;
19 | import static org.junit.Assert.assertFalse;
20 | import static org.junit.Assert.assertThat;
21 | import static org.junit.Assert.assertTrue;
22 |
23 | import java.io.File;
24 | import java.util.Collections;
25 | import java.util.HashMap;
26 | import java.util.List;
27 | import java.util.Map;
28 |
29 | import org.apache.hadoop.hive.conf.HiveConf;
30 | import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
31 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
32 | import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
33 | import org.apache.hadoop.hive.metastore.api.Database;
34 | import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
35 | import org.apache.thrift.TException;
36 | import org.junit.AfterClass;
37 | import org.junit.Before;
38 | import org.junit.Rule;
39 | import org.junit.Test;
40 |
41 | public class ThriftHiveMetaStoreJUnitRuleTest {
42 |
43 | public @Rule ThriftHiveMetaStoreJUnitRule defaultDbRule = new ThriftHiveMetaStoreJUnitRule();
44 | public @Rule ThriftHiveMetaStoreJUnitRule customDbRule = new ThriftHiveMetaStoreJUnitRule("my_test_database");
45 | public @Rule ThriftHiveMetaStoreJUnitRule customPropertiesRule = new ThriftHiveMetaStoreJUnitRule("custom_props_database", customConfProperties());
46 |
47 | private static File defaultTempRoot;
48 | private static File customTempRoot;
49 |
50 | private Map customConfProperties() {
51 | return Collections.singletonMap("my.custom.key", "my.custom.value");
52 | }
53 |
54 | @Before
55 | public void before() {
56 | defaultTempRoot = defaultDbRule.tempDir();
57 | assertTrue(defaultTempRoot.exists());
58 | customTempRoot = customDbRule.tempDir();
59 | assertTrue(customTempRoot.exists());
60 | }
61 |
62 | @Test
63 | public void hiveDefaultName() throws Exception {
64 | assertRuleInitialised(defaultDbRule);
65 | }
66 |
67 | @Test
68 | public void hiveCustomName() throws Exception {
69 | assertRuleInitialised(customDbRule);
70 | }
71 |
72 | private void assertRuleInitialised(ThriftHiveMetaStoreJUnitRule hive) throws Exception {
73 | String databaseName = hive.databaseName();
74 |
75 | Database database = hive.client().getDatabase(databaseName);
76 |
77 | assertThat(database.getName(), is(databaseName));
78 | File databaseFolder = new File(hive.warehouseDir(), databaseName);
79 | assertThat(new File(database.getLocationUri()) + "/", is(databaseFolder.toURI().toString()));
80 |
81 | assertThat(hive.getThriftConnectionUri(), is("thrift://localhost:" + hive.getThriftPort()));
82 | HiveConf conf = new HiveConf(hive.conf());
83 | conf.setVar(ConfVars.METASTOREURIS, hive.getThriftConnectionUri());
84 | HiveMetaStoreClient client = new HiveMetaStoreClient(conf);
85 | try {
86 | List databases = client.getAllDatabases();
87 | assertThat(databases.size(), is(2));
88 | assertThat(databases.get(0), is("default"));
89 | assertThat(databases.get(1), is(databaseName));
90 | } finally {
91 | client.close();
92 | }
93 | }
94 |
95 | @Test
96 | public void customProperties() {
97 | Map conf = new HashMap<>();
98 | conf.put("my.custom.key", "my.custom.value");
99 | HiveConf hiveConf = customPropertiesRule.conf();
100 | assertThat(hiveConf.get("my.custom.key"), is("my.custom.value"));
101 | }
102 |
103 | @Test(expected = AlreadyExistsException.class)
104 | public void createExistingDatabase() throws TException {
105 | defaultDbRule.createDatabase(defaultDbRule.databaseName());
106 | }
107 |
108 | @Test(expected = NullPointerException.class)
109 | public void createDatabaseNullName() throws TException {
110 | defaultDbRule.createDatabase(null);
111 | }
112 |
113 | @Test(expected = InvalidObjectException.class)
114 | public void createDatabaseInvalidName() throws TException {
115 | defaultDbRule.createDatabase("");
116 | }
117 |
118 | @Test
119 | public void thriftPort() {
120 | int thriftPort = 3333;
121 | defaultDbRule.setThriftPort(thriftPort);
122 | assertThat(defaultDbRule.getThriftPort(), is(thriftPort));
123 | }
124 |
125 | @AfterClass
126 | public static void afterClass() {
127 | assertFalse(defaultTempRoot.exists());
128 | assertFalse(customTempRoot.exists());
129 | }
130 |
131 | }
132 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 |
2 | ## [5.0.3] - 2025-07-21
3 | ### Changed
4 | - Switched to groupId `com.expediagroup`
5 |
6 | ## [5.0.1] - 2024-10-03
7 | ### Changed
8 | - Nothing changed, please ignore.
9 |
10 | ## [5.0.0] - 2021-03-01
11 | ### Changed
12 | - Hive version updated to `3.1.2` (was `2.3.7`) and Hadoop version updated to `3.1.0` (was `2.7.2`).
13 |
14 | ## [4.0.0] - 2021-02-09
15 | ### Fixed
16 | - Intermediate temporary folders now cleaned up as part of test lifecycle.
17 | - `HiveMetaStoreCore` performs a null check before attempting to close its metastore client.
18 |
19 | ### Changed
20 | - Hive version updated to `2.3.8` (was `2.3.7`).
21 | - `hive-exec` dependency changed to use `core` classifier to allow source code retrieval for easier debugging.
22 | - Hive's `METASTORE_CONNECTION_POOLING_TYPE` is now set to `"NONE"`.
23 | - Hive's `HIVESTATSAUTOGATHER` is now set to `false`.
24 | - Hive's `HIVE_SERVER2_LOGGING_OPERATION_ENABLED` is now set to `false`.
25 | - Various Derby, scratch and similar folders now configured to use a base temporary folder.
26 | - JUnit4 Rules now extend `TestWatcher` instead of `ExternalResource` to allow cleanup of temporary folders on test failures.
27 | - `BeejuCore` `tempDir()` returns base temporary test folder instead of temporary Hive warehouse dir.
28 | - `BeejuCore` returns temporary Hive warehouse dir via `warehouseDir()`.
29 | - JUnit5 Extensions `getTempDirectory()` returns base temporary test folder instead of temporary Hive warehouse dir.
30 | - JUnit5 Extensions return temporary Hive warehouse dir via `getWarehouseDirectory()`.
31 | - JUnit4 Rules `tempDir()` returns base temporary test folder instead of temporary Hive warehouse dir.
32 | - JUnit4 rules return temporary Hive warehouse dir via `warehouseDir()`.
33 | - `hotels-oss-parent` version updated to `6.1.0` (was `5.0.0`) to enable building with Java 11.
34 |
35 | ## [3.3.0] - 2020-10-23
36 | ### Changed
37 | - Allow passing in of "pre" and "post" configuration values so that BeeJU's defaults can be overridden.
38 | - JUnit version updated to `5.7.0` (was `5.5.2`).
39 | - `hotels-oss-parent` version updated to `5.0.0` (was `4.2.0`).
40 |
41 | ## [3.2.0] - 2020-10-14
42 | ### Added
43 | - Support for setting Thrift Hive Metastore port in tests.
44 | - A `ThriftHiveMetaStoreApp` which can be used to run the the Thrift Hive Metastore service locally.
45 |
46 | ### Changed
47 | - Changed visibility of `createDatabase()` method in `BeejuJUnitRule` from default to public (for external usage).
48 |
49 | ## [3.1.0] - 2020-05-13
50 | ### Changed
51 | - JUnit version updated to `5.5.2` (was `5.5.1`).
52 | - Depend on `junit-jupiter` (was `junit-jupiter-api`).
53 | - `hotels-oss-parent` version updated to `4.2.0` (was `4.1.0`).
54 | - Upgraded version of `hive.version` to `2.3.7` (was `2.3.4`). Allows BeeJU to be used on JDK>=9.
55 |
56 | ### Added
57 | - Support for setting Hive conf using arbitrary string as conf key.
58 |
59 | ## [3.0.1] - 2019-09-27
60 | ### Changed
61 | - `HiveMetaStoreJUnitExtension` and `HiveServer2JUnitExtension` constructors made public to allow access to classes outside of the extensions package.
62 |
63 | ## [3.0.0] - 2019-09-06
64 | ### Changed
65 | - JDK version upgrade to 1.8 (was 1.7).
66 |
67 | ### Added
68 | - JUnit5 extension class equivalents for all BeeJU Rules.
69 |
70 | ## [2.0.0] - 2019-09-02
71 | ### Added
72 | - Support for JUnit5 using `migration-support` dependency. NOTE - the transitive dependency for JUnit4 from Beeju has been removed so you must depend on it in your own POM.
73 |
74 | ### Changed
75 | - Excluded `org.pentaho.pentaho-aggdesigner-algorithm` dependency as it's not available in Maven Central.
76 | - `hotels-oss-parent` version updated to 4.1.0 (was 4.0.1).
77 |
78 | ## [1.3.2] - 2019-07-10
79 | ### Changed
80 | - Release process now uses HTTPS (was SSH) from build slaves to GitHub, no changes to code or functionality.
81 |
82 | ## [1.3.1] - 2019-04-11
83 | ### Changed
84 | - `hotels-oss-parent` version updated to 4.0.1 (was 2.3.5).
85 | - Refactored project to remove checkstyle and findbugs warnings, which does not impact functionality.
86 |
87 | ## [1.3.0] - 2018-12-18
88 | ### Changed
89 | - `log4j-slf4j-impl` transitive dependency excluded. See [#17](https://github.com/ExpediaGroup/beeju/issues/17).
90 | - Hive version upgraded to 2.3.4 (was 2.3.0) and transitive dependencies on HBase which in turn depended on JDK tools 1.7 excluded. See [#19](https://github.com/ExpediaGroup/beeju/issues/19).
91 | - `hotels-oss` parent pom upgraded to 2.3.3 (was 2.0.6). See [#19](https://github.com/ExpediaGroup/beeju/issues/19).
92 |
93 | ## [1.2.1] - 2017-11-09
94 | ### Changed
95 | - Change `ConfVars` added in Hive 2.x to their equivalent string.
96 |
97 | ## [1.2.0] - 2017-10-03
98 | ### Changed
99 | - Upgrade to Hive-2.3.0.
100 | - Upgrade parent POM to 2.0.3.
101 |
102 | ### Added
103 | - The rules now accept Hive configuration properties at construction time.
104 |
105 | ## [1.1.3] - 2017-09-25
106 | ### Changed
107 | - Depend on latest parent with test.arguments build parameter.
108 |
109 | ## [1.1.0] - 2017-08-18
110 | ### Changed
111 | - Upgrade to Hive-2.1.1, required a switch from HsqlDB to Derby (Hive no longer seems to support HsqlDB).
112 |
113 | ## [1.0.2]
114 | ### Changed
115 | - Upgrade parent POM to 1.1.1.
116 |
117 | ## [1.0.1]
118 | ### Added
119 | - Addition of `HiveServer2JUnitRule` rule to test against Hive Metastore using the JDBC API.
120 |
121 | ## [1.0.0]
122 | ### Added
123 | - First release: `HiveMetaStoreJUnitRule` and `ThriftHiveMetaStoreJUnitRule` rules to test a Hive Metastore connecting directly to the database and the Thrift API respectively.
124 |
--------------------------------------------------------------------------------
/src/test/java/com/hotels/beeju/core/BeejuCoreTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju.core;
17 |
18 | import static org.hamcrest.CoreMatchers.is;
19 | import static org.hamcrest.CoreMatchers.notNullValue;
20 | import static org.hamcrest.MatcherAssert.assertThat;
21 | import static org.junit.jupiter.api.Assertions.assertFalse;
22 |
23 | import java.io.IOException;
24 | import java.nio.file.Files;
25 | import java.util.HashMap;
26 | import java.util.Map;
27 |
28 | import org.apache.derby.jdbc.EmbeddedDriver;
29 | import org.apache.hadoop.hive.conf.HiveConf;
30 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
31 | import org.apache.hadoop.hive.metastore.api.Database;
32 | import org.junit.jupiter.api.AfterEach;
33 | import org.junit.jupiter.api.Test;
34 |
35 | public class BeejuCoreTest {
36 |
37 | private String preKey = "my.custom.pre.key";
38 | private String preValue = "my.custom.pre.value";
39 | private String postKey = "my.custom.post.key";
40 | private String postValue = "my.custom.post.value";
41 | private String coreOverrideValue = "user-that-core-will-override";
42 | private String confOverrideValue = "password-that-will-override-core";
43 |
44 | private final BeejuCore defaultCore = new BeejuCore();
45 | private final BeejuCore dbNameCore = new BeejuCore("test_db");
46 | private final BeejuCore dbNameAndMapConfCore = new BeejuCore("test_db_2", createPreConfigurationMap(),
47 | createPostConfigurationMap());
48 | private final BeejuCore dbNameAndHiveConfCore = new BeejuCore("test_db_2", createPreHiveConf(), createPostHiveConf());
49 |
50 | private Map createPreConfigurationMap() {
51 | Map conf = new HashMap<>();
52 | conf.put(preKey, preValue);
53 | conf.put(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME.toString(), coreOverrideValue);
54 | return conf;
55 | }
56 |
57 | private Map createPostConfigurationMap() {
58 | Map conf = new HashMap<>();
59 | conf.put(postKey, postValue);
60 | conf.put(HiveConf.ConfVars.METASTOREPWD.toString(), confOverrideValue);
61 | return conf;
62 | }
63 |
64 | private HiveConf createPreHiveConf() {
65 | HiveConf conf = new HiveConf();
66 | conf.clear();
67 | conf.set(preKey, preValue);
68 | conf.setVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME, coreOverrideValue);
69 | return conf;
70 | }
71 |
72 | private HiveConf createPostHiveConf() {
73 | HiveConf conf = new HiveConf();
74 | conf.clear();
75 | conf.set(postKey, postValue);
76 | conf.setVar(HiveConf.ConfVars.METASTOREPWD, confOverrideValue);
77 | return conf;
78 | }
79 |
80 | @AfterEach
81 | public void cleanUp() {
82 | defaultCore.cleanUp();
83 | dbNameCore.cleanUp();
84 | dbNameAndMapConfCore.cleanUp();
85 | dbNameAndHiveConfCore.cleanUp();
86 | }
87 |
88 | @Test
89 | public void initialisedDefaultConstructor() {
90 | assertThat(defaultCore.databaseName(), is("test_database"));
91 | }
92 |
93 | @Test
94 | public void initialisedDbNameConstructor() {
95 | assertThat(dbNameCore.databaseName(), is("test_db"));
96 | }
97 |
98 | @Test
99 | public void initialisedDbNameAndMapConfConstructor() {
100 | assertThat(dbNameAndMapConfCore.databaseName(), is("test_db_2"));
101 | assertThat(dbNameAndMapConfCore.conf().get(preKey), is(preValue));
102 | assertThat(dbNameAndMapConfCore.conf().get(postKey), is(postValue));
103 | // below still set to BeeJU default as pre-config not overridden
104 | assertThat(dbNameAndMapConfCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user"));
105 | // below overridden by post-config
106 | assertThat(dbNameAndMapConfCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is(confOverrideValue));
107 | }
108 |
109 | @Test
110 | public void initialisedDbNameAndHiveConfConstructor() {
111 | assertThat(dbNameAndHiveConfCore.databaseName(), is("test_db_2"));
112 | assertThat(dbNameAndHiveConfCore.conf().get(preKey), is(preValue));
113 | assertThat(dbNameAndHiveConfCore.conf().get(postKey), is(postValue));
114 | // below still set to BeeJU default as pre-config not overridden
115 | assertThat(dbNameAndHiveConfCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user"));
116 | // below overridden by post-config
117 | assertThat(dbNameAndHiveConfCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is(confOverrideValue));
118 | }
119 |
120 | @Test
121 | public void createDirectory() {
122 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTOREWAREHOUSE), is(defaultCore.warehouseDir().toString()));
123 | }
124 |
125 | @Test
126 | public void deleteDirectory() throws IOException {
127 | BeejuCore testCore = new BeejuCore();
128 | testCore.cleanUp();
129 | assertFalse(Files.exists(testCore.warehouseDir()));
130 | assertFalse(Files.exists(testCore.tempDir()));
131 | }
132 |
133 | @Test
134 | public void setHiveVar() {
135 | defaultCore.setHiveVar(HiveConf.ConfVars.METASTORECONNECTURLKEY, "test");
136 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORECONNECTURLKEY), is("test"));
137 | }
138 |
139 | @Test
140 | public void setHiveConf() {
141 | defaultCore.setHiveConf("my.custom.key", "test");
142 | assertThat(defaultCore.conf().get("my.custom.key"), is("test"));
143 | }
144 |
145 | @Test
146 | public void setHiveIntVar() {
147 | defaultCore.setHiveIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT, 00000);
148 | assertThat(defaultCore.conf().getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT), is(00000));
149 | }
150 |
151 | @Test
152 | public void checkConfig() {
153 | assertThat(defaultCore.driverClassName(), is(EmbeddedDriver.class.getName()));
154 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORECONNECTURLKEY), is(defaultCore.connectionURL()));
155 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_DRIVER),
156 | is(defaultCore.driverClassName()));
157 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME), is("db_user"));
158 | assertThat(defaultCore.conf().getVar(HiveConf.ConfVars.METASTOREPWD), is("db_password"));
159 | assertThat(defaultCore.conf().getBoolVar(HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF), is(true));
160 | assertThat(defaultCore.conf().get("datanucleus.schema.autoCreateAll"), is("true"));
161 | assertThat(defaultCore.conf().get("hive.metastore.schema.verification"), is("false"));
162 | assertThat(defaultCore.conf().get("hcatalog.hive.client.cache.disabled"), is("true"));
163 | }
164 |
165 | @Test
166 | public void createDatabase() throws Exception {
167 | String databaseName = "Another_DB";
168 |
169 | defaultCore.createDatabase(databaseName);
170 | HiveMetaStoreClient client = defaultCore.newClient();
171 | Database db = client.getDatabase(databaseName);
172 | client.close();
173 |
174 | assertThat(db, is(notNullValue()));
175 | assertThat(db.getName(), is(databaseName.toLowerCase()));
176 | assertThat(db.getLocationUri(), is(String.format("file:%s/%s", defaultCore.warehouseDir(), databaseName)));
177 | }
178 |
179 | }
180 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | 4.0.0
4 |
5 |
6 | com.expediagroup
7 | eg-oss-parent
8 | 3.0.1
9 |
10 |
11 | com.expediagroup
12 | beeju
13 | beeju
14 | jar
15 | 5.0.4-SNAPSHOT
16 | 2015
17 |
18 |
19 | scm:git:https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ExpediaGroup/beeju.git
20 | scm:git:https://${GIT_USERNAME}:${GIT_PASSWORD}@github.com/ExpediaGroup/beeju.git
21 | https://github.com/ExpediaGroup/beeju
22 | HEAD
23 |
24 |
25 |
26 | 3.1.0
27 | 3.1.2
28 | 0.9.1
29 | 1.8
30 | 5.7.0
31 | 1.3.2
32 | 2.5.3
33 |
34 |
35 |
36 |
37 |
38 | com.esotericsoftware
39 | kryo-shaded
40 | 3.0.3
41 |
42 |
43 | org.apache.hadoop
44 | hadoop-common
45 | ${hadoop.version}
46 |
47 |
48 | org.apache.hadoop
49 | hadoop-mapreduce-client-core
50 | ${hadoop.version}
51 |
52 |
53 | org.apache.hive
54 | hive-common
55 | ${hive.version}
56 |
57 |
58 | org.apache.logging.log4j
59 | log4j-slf4j-impl
60 |
61 |
62 |
63 |
64 | org.apache.hive
65 | hive-exec
66 | ${hive.version}
67 | core
68 |
69 |
70 | org.apache.logging.log4j
71 | log4j-slf4j-impl
72 |
73 |
74 | org.pentaho
75 | pentaho-aggdesigner-algorithm
76 |
77 |
78 |
79 |
80 | org.apache.hive
81 | hive-metastore
82 | ${hive.version}
83 |
84 |
85 | org.apache.hbase
86 | hbase-client
87 |
88 |
89 |
90 |
91 | org.apache.hive
92 | hive-service
93 | ${hive.version}
94 |
95 |
96 | org.apache.hbase
97 | *
98 |
99 |
100 | org.pentaho
101 | pentaho-aggdesigner-algorithm
102 |
103 |
104 |
105 |
106 | org.apache.hive
107 | hive-jdbc
108 | ${hive.version}
109 |
110 |
111 | org.apache.tez
112 | tez-common
113 | ${tez.version}
114 |
115 |
116 | org.apache.tez
117 | tez-dag
118 | ${tez.version}
119 |
120 |
121 | org.hamcrest
122 | hamcrest
123 | 2.2
124 | provided
125 |
126 |
127 | junit
128 | junit
129 | 4.13.1
130 | provided
131 |
132 |
133 | org.hamcrest
134 | hamcrest-core
135 |
136 |
137 |
138 |
139 | org.junit.jupiter
140 | junit-jupiter
141 | ${junit.jupiter.version}
142 | provided
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 | com.mycila
151 | license-maven-plugin
152 | ${license.maven.plugin.version}
153 |
154 |
155 |
156 | src/main/java/com/hotels/beeju/core/BeejuCore.java
157 | src/main/java/com/hotels/beeju/hiveserver2/RelaxedSQLStdHiveAuthorizerFactory.java
158 |
159 |
160 |
161 |
162 | org.sonatype.plugins
163 | nexus-staging-maven-plugin
164 | ${nexus.staging.maven.plugin.version}
165 | true
166 |
167 | sonatype-nexus-staging
168 | https://oss.sonatype.org/
169 | true
170 | 30
171 |
172 |
173 |
174 | org.apache.maven.plugins
175 | maven-release-plugin
176 | ${maven.release.plugin.version}
177 |
178 |
179 |
180 |
181 |
182 |
193 |
194 | org.apache.maven.plugins
195 | maven-surefire-plugin
196 | 2.22.2
197 |
198 |
199 |
200 | org.junit.platform
201 | junit-platform-surefire-provider
202 | ${junit.platform.version}
203 |
204 |
205 |
206 | org.junit.vintage
207 | junit-vintage-engine
208 | ${junit.jupiter.version}
209 |
210 |
211 |
212 | org.junit.jupiter
213 | junit-jupiter-engine
214 | ${junit.jupiter.version}
215 |
216 |
217 |
218 |
219 | org.jacoco
220 | jacoco-maven-plugin
221 |
222 |
223 |
224 | org/apache/hadoop/hive/ql/parse/HiveParser
225 |
226 |
227 |
228 |
229 |
230 |
231 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # BeeJU
2 | 
3 |
4 | # Start using
5 | You can obtain BeeJU from Maven Central:
6 |
7 | [](https://maven-badges.herokuapp.com/maven-central/com.expediagroup/beeju)  [](https://coveralls.io/github/ExpediaGroup/beeju) 
8 |
9 | # Overview
10 | BeeJU provides [JUnit5 Extensions](https://junit.org/junit5/docs/current/user-guide/#extensions) that can be used to write test code that tests [Hive](https://hive.apache.org/). The JUnit lifecycle extension points are a means to provide resources in a test and automatically tear them down when the life cycle of a test ends.
11 | This project is currently built with and tested against Hive 2.3.x (and minor versions back to Hive 1.2.1) but is most likely compatible with older and newer versions of Hive. The available JUnit extensions are explained in more detail below.
12 |
13 | BeeJU also provides [JUnit4 Rules](http://junit.org/junit4/javadoc/4.12/org/junit/Rule.html) that can be used in the same manner as the JUnit5 extensions. Examples of how to use both options can be found below.
14 | # Usage
15 | The BeeJU JUnit rules and extensions provide a way to run tests that have an underlying requirement to use the Hive Metastore API but don't have the ability to mock the [Hive Metastore Client](https://hive.apache.org/javadocs/r2.3.6/api/index.html). The rules and extensions spin up and tear down an in-memory Metastore which may add a few seconds to the test life cycle so if you require tests to run in the sub-second range this is not for you.
16 |
17 | ## Maven Dependencies
18 | Depend on BeeJU using:
19 |
20 | ```xml
21 |
22 | com.expediagroup
23 | beeju
24 | ....
25 | test
26 |
27 | ```
28 |
29 | ## Hive version compatibility
30 |
31 | This version of BeeJU is intended for use with Hive 3.1.2. For Hive 2.x support, please use BeeJU 4.0.0.
32 |
33 | ## JUnit5
34 | ### ThriftHiveMetaStoreJUnitExtension
35 | This extension creates an in-memory Hive database and a Thrift Hive Metastore service on top of this. This can then be used to perform Hive Thrift API calls in a test. The extension exposes a Thrift URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions.
36 |
37 | Example usage: Class under test creates a table via the Hive Metastore Thrift API.
38 |
39 | @RegisterExtension
40 | public ThriftHiveMetaStoreJUnitExtension hive = new ThriftHiveMetaStoreJUnitExtension("foo_db");
41 |
42 | @Test
43 | public void example() throws Exception {
44 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.getThriftConnectionUri());
45 | classUnderTest.createTable("foo_db", "bar_table");
46 |
47 | assertTrue(hive.client().tableExists("foo_db", "bar_table"));
48 | }
49 |
50 | ### HiveMetaStoreJUnitExtension
51 | This extension creates an in-memory Hive database without a Thrift Hive Metastore service. This can then be used to perform Hive API calls directly (i.e. without going via Hive's Metastore Thrift service) in a test.
52 |
53 | Example usage: Class under test creates a partition using an injected Hive Metastore Client.
54 |
55 | @RegisterExtension
56 | public HiveMetaStoreJUnitExtension hive = new HiveMetaStoreJUnitExtension("foo_db");
57 |
58 | @Test
59 | public void example() throws Exception {
60 | HiveMetaStoreClient client = hive.client();
61 | ClassUnderTest classUnderTest = new ClassUnderTest(client);
62 | Table table = new Table();
63 | table.setDbName("foo_db");
64 | table.setTableName("bar_table");
65 | hive.createTable(table);
66 |
67 | classUnderTest.createPartition(client, table);
68 |
69 | assertEquals(1, client.listPartitions("foo_db", "bar_table", (short) 100));
70 | }
71 |
72 | ### HiveServer2JUnitExtension
73 | This extension creates an in-memory Hive database, a Thrift Hive Metastore service on top of this and a HiveServer2 service. This can then be used to perform Hive JDBC calls in a test. The extension exposes a JDBC URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions.
74 |
75 | Example usage: Class under test drops a table via Hive JDBC.
76 |
77 | @RegisterExtension
78 | public HiveServer2JUnitExtension hive = new HiveServer2JUnitExtension("foo_db");
79 |
80 | @Test
81 | public void example() {
82 | Class.forName(hive.driverClassName());
83 | try (Connection connection = DriverManager.getConnection(hive.connectionURL());
84 | Statement statement = connection.createStatement()) {
85 | String createHql = new StringBuilder(256)
86 | .append("CREATE TABLE `foo_db.bar_table`(`id` int, `name` string) ")
87 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ")
88 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ")
89 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'")
90 | .toString();
91 | statement.execute(createHql);
92 | }
93 |
94 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.connectionURL());
95 | classUnderTest.dropTable("foo_db", "bar_table");
96 |
97 | HiveMetaStoreClient client = hive.newClient();
98 | try {
99 | assertFalse(client.tableExists("foo_db", "bar_table"));
100 | } finally {
101 | client.close();
102 | }
103 | }
104 |
105 | ## JUnit4
106 | For JUnit4, ensure you have the [JUnit4](https://github.com/junit-team/junit4) dependency in your POM, as BeeJU no longer supplies it as a transitive dependency.
107 |
108 | ### ThriftHiveMetaStoreJUnitRule
109 | This rule creates an in-memory Hive database and a Thrift Hive Metastore service on top of this. This can then be used to perform Hive Thrift API calls in a test. The rule exposes a Thrift URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions.
110 |
111 | Example `@Rule` usage: Class under test creates a table via the Hive Metastore Thrift API.
112 |
113 | @Rule
114 | public ThriftHiveMetaStoreJUnitRule hive = new ThriftHiveMetaStoreJUnitRule("foo_db");
115 |
116 | @Test
117 | public void example() throws Exception {
118 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.getThriftConnectionUri());
119 | classUnderTest.createTable("foo_db", "bar_table");
120 |
121 | assertTrue(hive.client().tableExists("foo_db", "bar_table"));
122 | }
123 |
124 | ### HiveMetaStoreJUnitRule
125 | This rule creates an in-memory Hive database without a Thrift Hive Metastore service. This can then be used to perform Hive API calls directly (i.e. without going via Hive's Metastore Thrift service) in a test.
126 |
127 | Example `@Rule` usage: Class under test creates a partition using an injected Hive Metastore Client.
128 |
129 | @Rule
130 | public HiveMetaStoreJUnitRule hive = new HiveMetaStoreJUnitRule("foo_db");
131 |
132 | @Test
133 | public void example() throws Exception {
134 | HiveMetaStoreClient client = hive.client();
135 | ClassUnderTest classUnderTest = new ClassUnderTest(client);
136 | Table table = new Table();
137 | table.setDbName("foo_db");
138 | table.setTableName("bar_table");
139 | hive.createTable(table);
140 |
141 | classUnderTest.createPartition(client, table);
142 |
143 | assertEquals(1, client.listPartitions("foo_db", "bar_table", (short) 100));
144 | }
145 |
146 | ### HiveServer2JUnitRule
147 | This rule creates an in-memory Hive database, a Thrift Hive Metastore service on top of this and a HiveServer2 service. This can then be used to perform Hive JDBC calls in a test. The rule exposes a JDBC URI that can be injected into the class under test and a Hive Metastore Client which can be used for data setup and assertions.
148 |
149 | Example `@Rule` usage: Class under test drops a table via Hive JDBC.
150 |
151 | @Rule
152 | public HiveServer2JUnitRule hive = new HiveServer2JUnitRule("foo_db");
153 |
154 | @Test
155 | public void example() {
156 | Class.forName(hive.driverClassName());
157 | try (Connection connection = DriverManager.getConnection(hive.connectionURL());
158 | Statement statement = connection.createStatement()) {
159 | String createHql = new StringBuilder(256)
160 | .append("CREATE TABLE `foo_db.bar_table`(`id` int, `name` string) ")
161 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ")
162 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ")
163 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'")
164 | .toString();
165 | statement.execute(createHql);
166 | }
167 |
168 | ClassUnderTest classUnderTest = new ClassUnderTest(hive.connectionURL());
169 | classUnderTest.dropTable("foo_db", "bar_table");
170 |
171 | HiveMetaStoreClient client = hive.newClient();
172 | try {
173 | assertFalse(client.tableExists("foo_db", "bar_table"));
174 | } finally {
175 | client.close();
176 | }
177 | }
178 |
179 | ## JUnit5 Rule Migration
180 | Support is available to enable you to migrate your JUnit4 tests that currently use BeeJU rules without changing them to use extensions. To use JUnit5, ensure you have the following dependency in your POM:
181 |
182 | ```xml
183 |
184 | org.junit.jupiter
185 | junit-jupiter-migrationsupport
186 | ${junit.jupiter.version}
187 | test
188 |
189 | ```
190 |
191 | For any test classes using the BeeJU rules, add the class annotation `@EnableRuleMigrationSupport`. No further changes are needed to move your JUnit4 tests to JUnit5.
192 |
193 | # Legal
194 | This project is available under the [Apache 2.0 License](http://www.apache.org/licenses/LICENSE-2.0.html).
195 |
196 | Copyright 2016-2021 Expedia, Inc.
197 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------
/src/main/java/com/hotels/beeju/core/BeejuCore.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc. and Klarna AB.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju.core;
17 |
18 | import static com.google.common.base.Preconditions.checkNotNull;
19 |
20 | import java.io.File;
21 | import java.io.IOException;
22 | import java.io.UncheckedIOException;
23 | import java.net.ServerSocket;
24 | import java.nio.file.Files;
25 | import java.nio.file.Path;
26 | import java.util.Collections;
27 | import java.util.HashMap;
28 | import java.util.Iterator;
29 | import java.util.Map;
30 | import java.util.Map.Entry;
31 | import java.util.UUID;
32 | import java.util.concurrent.TimeUnit;
33 |
34 | import org.apache.commons.io.FileUtils;
35 | import org.apache.derby.jdbc.EmbeddedDriver;
36 | import org.apache.hadoop.fs.FileUtil;
37 | import org.apache.hadoop.fs.permission.FsPermission;
38 | import org.apache.hadoop.hive.conf.HiveConf;
39 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
40 | import org.apache.hadoop.hive.metastore.api.Database;
41 | import org.apache.hadoop.hive.metastore.api.MetaException;
42 | import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
43 | import org.apache.thrift.TException;
44 | import org.slf4j.Logger;
45 | import org.slf4j.LoggerFactory;
46 |
47 | // This class contains some code sourced from and inspired by HiveRunner, specifically
48 | // https://github.com/klarna/HiveRunner/blob/fb00a98f37abdb779547c1c98ef6fbe54d373e0c/src/main/java/com/klarna/hiverunner/StandaloneHiveServerContext.java
49 | public class BeejuCore {
50 |
51 | private static final Logger log = LoggerFactory.getLogger(BeejuCore.class);
52 |
53 | // "user" conflicts with USER db and the metastore_db can't be created.
54 | private static final String METASTORE_DB_USER = "db_user";
55 | private static final String METASTORE_DB_PASSWORD = "db_password";
56 |
57 | protected final HiveConf conf = new HiveConf();
58 | private final String databaseName;
59 | private String connectionURL;
60 | private String driverClassName;
61 | private Path warehouseDir;
62 | private Path derbyHome;
63 | private Path baseDir;
64 |
65 | private static Map convertToMap(HiveConf hiveConf) {
66 | Map converted = new HashMap();
67 | Iterator> iterator = hiveConf.iterator();
68 | while (iterator.hasNext()) {
69 | Entry next = iterator.next();
70 | converted.put(next.getKey(), next.getValue());
71 | }
72 | return converted;
73 | }
74 |
75 | public BeejuCore() {
76 | this("test_database");
77 | }
78 |
79 | public BeejuCore(String databaseName) {
80 | this(databaseName, Collections.emptyMap());
81 | }
82 |
83 | public BeejuCore(String databaseName, HiveConf preConfiguration, HiveConf postConfiguration) {
84 | this(databaseName, convertToMap(preConfiguration), convertToMap(postConfiguration));
85 | }
86 |
87 | public BeejuCore(String databaseName, Map preConfiguration) {
88 | this(databaseName, preConfiguration, Collections.emptyMap());
89 | }
90 |
91 | public BeejuCore(String databaseName, Map preConfiguration, Map postConfiguration) {
92 | checkNotNull(databaseName, "databaseName is required");
93 | this.databaseName = databaseName;
94 | configure(preConfiguration);
95 |
96 | configureFolders();
97 |
98 | configureMetastore();
99 |
100 | configureMisc();
101 |
102 | configure(postConfiguration);
103 | }
104 |
105 | private void configureMisc() {
106 | int webUIPort = getWebUIPort();
107 |
108 | // override default port as some of our test environments claim it is in use.
109 | conf.setIntVar(HiveConf.ConfVars.HIVE_SERVER2_WEBUI_PORT, webUIPort);
110 |
111 | conf.setBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER, false);
112 |
113 | // Disable to get rid of clean up exception when stopping the Session.
114 | conf.setBoolVar(HiveConf.ConfVars.HIVE_SERVER2_LOGGING_OPERATION_ENABLED, false);
115 |
116 | // Used to prevent "Not authorized to make the get_current_notificationEventId call" errors
117 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.EVENT_DB_NOTIFICATION_API_AUTH, "false");
118 |
119 | // Used to prevent "Error polling for notification events" error
120 | conf.setTimeVar(HiveConf.ConfVars.HIVE_NOTFICATION_EVENT_POLL_INTERVAL, 0, TimeUnit.MILLISECONDS);
121 |
122 | // Has to be added to exclude failures related to the HiveMaterializedViewsRegistry
123 | conf.set(HiveConf.ConfVars.HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL.varname, "DUMMY");
124 | System.setProperty(HiveConf.ConfVars.HIVE_SERVER2_MATERIALIZED_VIEWS_REGISTRY_IMPL.varname, "DUMMY");
125 | }
126 |
127 | private void setMetastoreAndSystemProperty(MetastoreConf.ConfVars key, String value) {
128 | conf.set(key.getVarname(), value);
129 | conf.set(key.getHiveName(), value);
130 |
131 | System.setProperty(key.getVarname(), value);
132 | System.setProperty(key.getHiveName(), value);
133 | }
134 |
135 | private int getWebUIPort() {
136 | // Try to find a free port, if impossible return the default port 0 which disables the WebUI altogether
137 | int defaultPort = 0;
138 |
139 | try (ServerSocket socket = new ServerSocket(0)) {
140 | return socket.getLocalPort();
141 | } catch (IOException e) {
142 | log.info(
143 | "No free port available for the Web UI. Setting the port to " + defaultPort + ", which disables the WebUI.",
144 | e);
145 | return defaultPort;
146 | }
147 | }
148 |
149 | private void configureFolders() {
150 | try {
151 | baseDir = Files.createTempDirectory("beeju-basedir-");
152 | createAndSetFolderProperty(HiveConf.ConfVars.SCRATCHDIR, "scratchdir");
153 | createAndSetFolderProperty(HiveConf.ConfVars.LOCALSCRATCHDIR, "localscratchdir");
154 | createAndSetFolderProperty(HiveConf.ConfVars.HIVEHISTORYFILELOC, "hive-history");
155 |
156 | createDerbyPaths();
157 | createWarehousePath();
158 | } catch (IOException e) {
159 | throw new UncheckedIOException("Error creating temporary folders", e);
160 | }
161 | }
162 |
163 | private void configureMetastore() {
164 | driverClassName = EmbeddedDriver.class.getName();
165 | conf.setBoolean("hcatalog.hive.client.cache.disabled", true);
166 | connectionURL = "jdbc:derby:memory:" + UUID.randomUUID() + ";create=true";
167 |
168 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECT_URL_KEY, connectionURL);
169 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECTION_DRIVER, driverClassName);
170 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.CONNECTION_USER_NAME, METASTORE_DB_USER);
171 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.PWD, METASTORE_DB_PASSWORD);
172 |
173 | conf.setVar(HiveConf.ConfVars.METASTORE_CONNECTION_POOLING_TYPE, "NONE");
174 | conf.setBoolVar(HiveConf.ConfVars.HMSHANDLERFORCERELOADCONF, true);
175 |
176 | // Hive 2.x compatibility
177 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.AUTO_CREATE_ALL, "true");
178 | setMetastoreAndSystemProperty(MetastoreConf.ConfVars.SCHEMA_VERIFICATION, "false");
179 | }
180 |
181 | private void createAndSetFolderProperty(HiveConf.ConfVars var, String childFolderName) throws IOException {
182 | String folderPath = newFolder(baseDir, childFolderName).toAbsolutePath().toString();
183 | conf.setVar(var, folderPath);
184 | }
185 |
186 | private Path newFolder(Path basedir, String folder) throws IOException {
187 | Path newFolder = Files.createTempDirectory(basedir, folder);
188 | FileUtil.setPermission(newFolder.toFile(), FsPermission.getDirDefault());
189 | return newFolder;
190 | }
191 |
192 | private void createDerbyPaths() throws IOException {
193 | derbyHome = Files.createTempDirectory(baseDir, "derby-home-");
194 | System.setProperty("derby.system.home", derbyHome.toString());
195 |
196 | // overriding default derby log path to go to tmp
197 | String derbyLog = Files.createTempFile(baseDir, "derby", ".log").toString();
198 | System.setProperty("derby.stream.error.file", derbyLog);
199 | }
200 |
201 | private void createWarehousePath() throws IOException {
202 | warehouseDir = Files.createTempDirectory(baseDir, "hive-warehouse-");
203 | setHiveVar(HiveConf.ConfVars.METASTOREWAREHOUSE, warehouseDir.toString());
204 | }
205 |
206 | public void cleanUp() {
207 | deleteDirectory(baseDir);
208 | }
209 |
210 | private void deleteDirectory(Path path) {
211 | try {
212 | FileUtils.deleteDirectory(path.toFile());
213 | } catch (IOException e) {
214 | log.warn("Error cleaning up " + path, e);
215 | }
216 | }
217 |
218 | private void configure(Map customConfiguration) {
219 | if (customConfiguration != null) {
220 | for (Map.Entry entry : customConfiguration.entrySet()) {
221 | conf.set(entry.getKey(), entry.getValue());
222 | }
223 | }
224 | }
225 |
226 | void setHiveVar(HiveConf.ConfVars variable, String value) {
227 | conf.setVar(variable, value);
228 | }
229 |
230 | void setHiveConf(String variable, String value) {
231 | conf.set(variable, value);
232 | }
233 |
234 | void setHiveIntVar(HiveConf.ConfVars variable, int value) {
235 | conf.setIntVar(variable, value);
236 | }
237 |
238 | /**
239 | * Create a new database with the specified name.
240 | *
241 | * @param databaseName Database name.
242 | * @throws TException If an error occurs creating the database.
243 | */
244 | public void createDatabase(String databaseName) throws TException {
245 | File tempFile = warehouseDir.toFile();
246 | String databaseFolder = new File(tempFile, databaseName).toURI().toString();
247 | HiveMetaStoreClient client = newClient();
248 | try {
249 | client.createDatabase(new Database(databaseName, null, databaseFolder, null));
250 | } finally {
251 | client.close();
252 | }
253 | }
254 |
255 | /**
256 | * @return a copy of the {@link HiveConf} used to create the Hive Metastore database. This {@link HiveConf} should be
257 | * used by tests wishing to connect to the database.
258 | */
259 | public HiveConf conf() {
260 | return new HiveConf(conf);
261 | }
262 |
263 | /**
264 | * @return the name of the pre-created database.
265 | */
266 | public String databaseName() {
267 | return databaseName;
268 | }
269 |
270 | /**
271 | * @return the name of the JDBC driver class used to access the database.
272 | */
273 | public String driverClassName() {
274 | return driverClassName;
275 | }
276 |
277 | /**
278 | * @return the JDBC connection URL to the HSQLDB in-memory database.
279 | */
280 | public String connectionURL() {
281 | return connectionURL;
282 | }
283 |
284 | public Path tempDir() {
285 | return baseDir;
286 | }
287 |
288 | public Path warehouseDir() {
289 | return warehouseDir;
290 | }
291 |
292 | /**
293 | * Creates a new HiveMetaStoreClient that can talk directly to the backed metastore database.
294 | *
295 | * The invoker is responsible for closing the client.
296 | *
297 | *
298 | * @return the {@link HiveMetaStoreClient} backed by an HSQLDB in-memory database.
299 | */
300 | public HiveMetaStoreClient newClient() {
301 | try {
302 | return new HiveMetaStoreClient(conf);
303 | } catch (MetaException e) {
304 | throw new RuntimeException("Unable to create HiveMetaStoreClient", e);
305 | }
306 | }
307 | }
308 |
--------------------------------------------------------------------------------
/src/test/java/com/hotels/beeju/core/HiveServer2CoreTest.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) 2015-2021 Expedia, Inc.
3 | *
4 | * Licensed under the Apache License, Version 2.0 (the "License");
5 | * you may not use this file except in compliance with the License.
6 | * You may obtain a copy of the License at
7 | *
8 | * http://www.apache.org/licenses/LICENSE-2.0
9 | *
10 | * Unless required by applicable law or agreed to in writing, software
11 | * distributed under the License is distributed on an "AS IS" BASIS,
12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 | * See the License for the specific language governing permissions and
14 | * limitations under the License.
15 | */
16 | package com.hotels.beeju.core;
17 |
18 | import static org.hamcrest.CoreMatchers.is;
19 | import static org.hamcrest.MatcherAssert.assertThat;
20 | import static org.junit.jupiter.api.Assertions.assertEquals;
21 | import static org.junit.jupiter.api.Assertions.fail;
22 |
23 | import java.io.IOException;
24 | import java.sql.Connection;
25 | import java.sql.DriverManager;
26 | import java.sql.ResultSet;
27 | import java.sql.Statement;
28 | import java.util.Arrays;
29 | import java.util.List;
30 |
31 | import org.apache.hadoop.hive.conf.HiveConf;
32 | import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
33 | import org.apache.hadoop.hive.metastore.api.FieldSchema;
34 | import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
35 | import org.apache.hadoop.hive.metastore.api.Partition;
36 | import org.apache.hadoop.hive.metastore.api.SerDeInfo;
37 | import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
38 | import org.apache.hadoop.hive.metastore.api.Table;
39 | import org.apache.hive.service.Service;
40 | import org.apache.thrift.TException;
41 | import org.junit.jupiter.api.AfterEach;
42 | import org.junit.jupiter.api.BeforeEach;
43 | import org.junit.jupiter.api.Test;
44 |
45 | public class HiveServer2CoreTest {
46 |
47 | private static final String DATABASE = "my_test_db";
48 | private final BeejuCore core = new BeejuCore(DATABASE);
49 | private final HiveServer2Core server = new HiveServer2Core(core);
50 |
51 | @BeforeEach
52 | public void beforeEach() throws InterruptedException, IOException, TException {
53 | server.startServerSocket();
54 | server.initialise();
55 | server.getCore().createDatabase(DATABASE);
56 | }
57 |
58 | @AfterEach
59 | public void afterEach() {
60 | server.shutdown();
61 | core.cleanUp();
62 | }
63 |
64 | @Test
65 | public void initiateServer() {
66 | assertThat(server.getJdbcConnectionUrl(),
67 | is("jdbc:hive2://localhost:" + server.getPort() + "/" + core.databaseName()));
68 | assertThat(server.getHiveServer2().getServiceState(), is(Service.STATE.STARTED));
69 | }
70 |
71 | @Test
72 | public void closeServer() throws InterruptedException {
73 | server.shutdown();
74 |
75 | assertThat(server.getHiveServer2().getServiceState(), is(Service.STATE.STOPPED));
76 | }
77 |
78 | @Test
79 | public void startServerSocket() {
80 | assertEquals(core.conf().getIntVar(HiveConf.ConfVars.HIVE_SERVER2_THRIFT_PORT), server.getPort());
81 | }
82 |
83 | @Test
84 | public void dropTable() throws Exception {
85 | String tableName = "my_drop_table";
86 | createUnpartitionedTable(DATABASE, tableName, server);
87 |
88 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
89 | Statement statement = connection.createStatement()) {
90 | String dropHql = String.format("DROP TABLE %s.%s", DATABASE, tableName);
91 | statement.execute(dropHql);
92 | }
93 |
94 | HiveMetaStoreClient client = server.getCore().newClient();
95 | try {
96 | client.getTable(DATABASE, tableName);
97 | fail(String.format("Table %s.%s was not deleted", DATABASE, tableName));
98 | } catch (NoSuchObjectException e) {
99 | // expected
100 | } finally {
101 | client.close();
102 | }
103 | }
104 |
105 | @Test
106 | public void createTable() throws Exception {
107 | String tableName = "my_test_table";
108 |
109 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
110 | Statement statement = connection.createStatement()) {
111 | String createHql = new StringBuilder()
112 | .append("CREATE TABLE `" + DATABASE + "." + tableName + "`(`id` int, `name` string) ")
113 | .append("ROW FORMAT SERDE 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' ")
114 | .append("STORED AS INPUTFORMAT 'org.apache.hadoop.mapred.TextInputFormat' ")
115 | .append("OUTPUTFORMAT 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'")
116 | .toString();
117 | statement.execute(createHql);
118 | }
119 |
120 | HiveMetaStoreClient client = server.getCore().newClient();
121 | Table table = client.getTable(DATABASE, tableName);
122 | client.close();
123 | assertThat(table.getDbName(), is(DATABASE));
124 | assertThat(table.getTableName(), is(tableName));
125 | assertThat(table.getSd().getCols(),
126 | is(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null))));
127 | assertThat(table.getSd().getInputFormat(), is("org.apache.hadoop.mapred.TextInputFormat"));
128 | assertThat(table.getSd().getOutputFormat(), is("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat"));
129 | assertThat(table.getSd().getSerdeInfo().getSerializationLib(),
130 | is("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe"));
131 | }
132 |
133 | @Test
134 | public void showCreateTable() throws Exception {
135 | String tableName = "my_show_table";
136 | Table table = createUnpartitionedTable(DATABASE, tableName, server);
137 |
138 | StringBuilder showCreateTable = new StringBuilder();
139 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
140 | Statement statement = connection.createStatement()) {
141 | String showHql = String.format("SHOW CREATE TABLE %s.%s", DATABASE, tableName);
142 | ResultSet result = statement.executeQuery(showHql);
143 | while (result.next()) {
144 | showCreateTable.append(result.getString(1)).append("\n");
145 | }
146 | result.close();
147 | }
148 | String expectedShowCreateTable = new StringBuilder()
149 | .append("CREATE TABLE `my_test_db." + tableName + "`(\n")
150 | .append(" `id` int, \n")
151 | .append(" `name` string)\n")
152 | .append("ROW FORMAT SERDE \n")
153 | .append(" 'org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe' \n")
154 | .append("STORED AS INPUTFORMAT \n")
155 | .append(" 'org.apache.hadoop.mapred.TextInputFormat' \n")
156 | .append("OUTPUTFORMAT \n")
157 | .append(" 'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'\n")
158 | .append("LOCATION\n")
159 | .append(" 'file:" + server.getCore().warehouseDir() + "/" + DATABASE + "/" + tableName + "'\n")
160 | .append("TBLPROPERTIES (\n")
161 | .append(" 'transient_lastDdlTime'='" + table.getParameters().get("transient_lastDdlTime") + "')\n")
162 | .toString();
163 | assertThat(showCreateTable.toString(), is(expectedShowCreateTable));
164 | }
165 |
166 | @Test
167 | public void dropDatabase() throws Exception {
168 | String databaseName = "Another_DB";
169 |
170 | server.getCore().createDatabase(databaseName);
171 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
172 | Statement statement = connection.createStatement()) {
173 | String dropHql = String.format("DROP DATABASE %s", databaseName);
174 | statement.execute(dropHql);
175 | }
176 |
177 | HiveMetaStoreClient client = server.getCore().newClient();
178 | try {
179 | client.getDatabase(databaseName);
180 | fail(String.format("Database %s was not deleted", databaseName));
181 | } catch (NoSuchObjectException e) {
182 | // expected
183 | } finally {
184 | client.close();
185 | }
186 | }
187 |
188 | @Test
189 | public void addPartition() throws Exception {
190 | String tableName = "my_add_part_table";
191 | createPartitionedTable(DATABASE, tableName, server);
192 |
193 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
194 | Statement statement = connection.createStatement()) {
195 | String addPartitionHql = String.format("ALTER TABLE %s.%s ADD PARTITION (partcol=1)", DATABASE, tableName);
196 | statement.execute(addPartitionHql);
197 | }
198 |
199 | HiveMetaStoreClient client = server.getCore().newClient();
200 | try {
201 | List partitions = client.listPartitions(DATABASE, tableName, (short) -1);
202 | assertThat(partitions.size(), is(1));
203 | assertThat(partitions.get(0).getDbName(), is(DATABASE));
204 | assertThat(partitions.get(0).getTableName(), is(tableName));
205 | assertThat(partitions.get(0).getValues(), is(Arrays.asList("1")));
206 | assertThat(partitions.get(0).getSd().getLocation(),
207 | is(String.format("file:%s/%s/%s/partcol=1", server.getCore().warehouseDir(), DATABASE, tableName)));
208 | } finally {
209 | client.close();
210 | }
211 | }
212 |
213 | @Test
214 | public void dropPartition() throws Exception {
215 | String tableName = "my_drop_part_table";
216 | HiveMetaStoreClient client = server.getCore().newClient();
217 |
218 | try {
219 | Table table = createPartitionedTable(DATABASE, tableName, server);
220 |
221 | Partition partition = new Partition();
222 | partition.setDbName(DATABASE);
223 | partition.setTableName(tableName);
224 | partition.setValues(Arrays.asList("1"));
225 | partition.setSd(new StorageDescriptor(table.getSd()));
226 | partition
227 | .getSd()
228 | .setLocation(String.format("file:%s/%s/%s/partcol=1", server.getCore().warehouseDir(), DATABASE, tableName));
229 | client.add_partition(partition);
230 |
231 | try (Connection connection = DriverManager.getConnection(server.getJdbcConnectionUrl());
232 | Statement statement = connection.createStatement()) {
233 | String dropPartitionHql = String.format("ALTER TABLE %s.%s DROP PARTITION (partcol=1)", DATABASE, tableName);
234 | statement.execute(dropPartitionHql);
235 | }
236 |
237 | List partitions = client.listPartitions(DATABASE, tableName, (short) -1);
238 | assertThat(partitions.size(), is(0));
239 | } finally {
240 | client.close();
241 | }
242 | }
243 |
244 | private Table createUnpartitionedTable(String databaseName, String tableName, HiveServer2Core server)
245 | throws Exception {
246 | Table table = new Table();
247 | table.setDbName(databaseName);
248 | table.setTableName(tableName);
249 | table.setSd(new StorageDescriptor());
250 | table.getSd().setCols(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null)));
251 | table.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
252 | table.getSd().setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat");
253 | table.getSd().setSerdeInfo(new SerDeInfo());
254 | table.getSd().getSerdeInfo().setSerializationLib("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe");
255 | HiveMetaStoreClient client = server.getCore().newClient();
256 | client.createTable(table);
257 | client.close();
258 | return table;
259 | }
260 |
261 | private Table createPartitionedTable(String databaseName, String tableName, HiveServer2Core server) throws Exception {
262 | Table table = new Table();
263 | table.setDbName(DATABASE);
264 | table.setTableName(tableName);
265 | table.setPartitionKeys(Arrays.asList(new FieldSchema("partcol", "int", null)));
266 | table.setSd(new StorageDescriptor());
267 | table.getSd().setCols(Arrays.asList(new FieldSchema("id", "int", null), new FieldSchema("name", "string", null)));
268 | table.getSd().setInputFormat("org.apache.hadoop.mapred.TextInputFormat");
269 | table.getSd().setOutputFormat("org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat");
270 | table.getSd().setSerdeInfo(new SerDeInfo());
271 | table.getSd().getSerdeInfo().setSerializationLib("org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe");
272 | HiveMetaStoreClient client = server.getCore().newClient();
273 | client.createTable(table);
274 | client.close();
275 | return table;
276 | }
277 |
278 | }
279 |
--------------------------------------------------------------------------------