http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/StringUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/StringUtilsTest.java b/utils/src/test/java/com/cloud/utils/StringUtilsTest.java new file mode 100644 index 0000000..3619ede --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/StringUtilsTest.java @@ -0,0 +1,253 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.Arrays; + +import org.junit.Test; + +public class StringUtilsTest { + + @Test + public void testGetPreferredCharset() { + final boolean ifUtf8Supported = StringUtils.isUtf8Supported(); + if (ifUtf8Supported) { + assertEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8")); + } else { + assertNotEquals(StringUtils.getPreferredCharset(), Charset.forName("UTF-8")); + } + } + + @Test + public void testGetDefaultCharset() { + // Is this test irrelevant? Is wrapping the Charset.defaultCharset() too much? + // This test was added in order to cover the new StringUtils.getDefaultCharset(). + // One cannot be sure that StringUtils.getPreferredCharset() will always be + // equals to Charset.defaultCharset() + assertEquals(StringUtils.getDefaultCharset(), Charset.defaultCharset()); + } + + @Test + public void testCleanPasswordFromJsonObjectAtEnd() { + final String input = "{\"foo\":\"bar\",\"password\":\"test\"}"; + //TODO: It would be nice to clean up the regex in question to not + //have to return the trailing comma in the expected string below + final String expected = "{\"foo\":\"bar\",}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromJsonObjectInMiddle() { + final String input = "{\"foo\":\"bar\",\"password\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromJsonObjectAlone() { + final String input = "{\"password\":\"test\"}"; + final String expected = "{}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromJsonObjectAtStart() { + final String input = "{\"password\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromJsonObjectWithMultiplePasswords() { + final String input = "{\"description\":\"foo\"}],\"password\":\"bar\",\"nic\":[{\"password\":\"bar2\",\"id\":\"1\"}]}"; + final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromRequestString() { + final String input = "username=foo&password=bar&url=foobar"; + final String expected = "username=foo&url=foobar"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromEncodedRequestString() { + final String input = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26password%3DXXXXX%40123%26domain%3DBLR"; + final String expected = "name=SS1&provider=SMB&zoneid=5a60af2b-3025-4f2a-9ecc-8e33bf2b94e3&url=cifs%3A%2F%2F10.102.192.150%2FSMB-Share%2Fsowmya%2Fsecondary%3Fuser%3Dsowmya%26domain%3DBLR"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromRequestStringWithMultiplePasswords() { + final String input = "username=foo&password=bar&url=foobar&password=bar2&test=4"; + final String expected = "username=foo&url=foobar&test=4"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromRequestStringMatchedAtEndSingleQuote() { + final String input = "'username=foo&password=bar'"; + final String expected = "'username=foo'"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromRequestStringMatchedAtEndDoubleQuote() { + final String input = "\"username=foo&password=bar\""; + final String expected = "\"username=foo\""; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanPasswordFromRequestStringMatchedAtMiddleDoubleQuote() { + final String input = "\"username=foo&password=bar&goo=sdf\""; + final String expected = "\"username=foo&goo=sdf\""; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testJoin() { + assertEquals("a-b-c", StringUtils.join("-", "a", "b", "c")); + assertEquals("", StringUtils.join("-")); + } + + @Test + public void testCleanSecretkeyFromJsonObjectAtEnd() { + final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\"}"; + // TODO: It would be nice to clean up the regex in question to not + // have to return the trailing comma in the expected string below + final String expected = "{\"foo\":\"bar\",}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanSecretkeyFromJsonObjectInMiddle() { + final String input = "{\"foo\":\"bar\",\"secretkey\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanSecretkeyFromJsonObjectAlone() { + final String input = "{\"secretkey\":\"test\"}"; + final String expected = "{}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanSecretkeyFromJsonObjectAtStart() { + final String input = "{\"secretkey\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanSecretkeyFromJsonObjectWithMultiplePasswords() { + final String input = "{\"description\":\"foo\"}],\"secretkey\":\"bar\",\"nic\":[{\"secretkey\":\"bar2\",\"id\":\"1\"}]}"; + final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromJsonObjectAtEnd() { + final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\"}"; + // TODO: It would be nice to clean up the regex in question to not + // have to return the trailing comma in the expected string below + final String expected = "{\"foo\":\"bar\",}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromJsonObjectInMiddle() { + final String input = "{\"foo\":\"bar\",\"accesskey\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"foo\":\"bar\",\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromJsonObjectAlone() { + final String input = "{\"accesskey\":\"test\"}"; + final String expected = "{}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromJsonObjectAtStart() { + final String input = "{\"accesskey\":\"test\",\"test\":\"blah\"}"; + final String expected = "{\"test\":\"blah\"}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromJsonObjectWithMultiplePasswords() { + final String input = "{\"description\":\"foo\"}],\"accesskey\":\"bar\",\"nic\":[{\"accesskey\":\"bar2\",\"id\":\"1\"}]}"; + final String expected = "{\"description\":\"foo\"}],\"nic\":[{\"id\":\"1\"}]}"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanAccesskeyFromRequestString() { + final String input = "username=foo&accesskey=bar&url=foobar"; + final String expected = "username=foo&url=foobar"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void testCleanSecretkeyFromRequestString() { + final String input = "username=foo&secretkey=bar&url=foobar"; + final String expected = "username=foo&url=foobar"; + final String result = StringUtils.cleanString(input); + assertEquals(result, expected); + } + + @Test + public void listToCsvTags() { + assertEquals("a,b,c", StringUtils.listToCsvTags(Arrays.asList("a","b", "c"))); + assertEquals("", StringUtils.listToCsvTags(new ArrayList<String>())); + } +}
http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/TernaryTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/TernaryTest.java b/utils/src/test/java/com/cloud/utils/TernaryTest.java new file mode 100644 index 0000000..cacbecb --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/TernaryTest.java @@ -0,0 +1,34 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import org.junit.Assert; +import org.junit.Test; + +public class TernaryTest { + @Test + public void testEquals() { + Assert.assertEquals(new Ternary<String, String, String>("a", "b", "c"), new Ternary<String, String, String>("a", "b", "c")); + Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Ternary<String, String, String>("a", "b", "d"))); + Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals("")); + Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(null)); + Assert.assertFalse(new Ternary<String, String, String>("a", "b", "c").equals(new Pair<String, String>("a", "b"))); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/TestProfiler.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/TestProfiler.java b/utils/src/test/java/com/cloud/utils/TestProfiler.java new file mode 100644 index 0000000..2306cd7 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/TestProfiler.java @@ -0,0 +1,116 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import org.apache.log4j.Logger; +import org.junit.Assert; +import org.junit.Test; + +import com.cloud.utils.testcase.Log4jEnabledTestCase; + +public class TestProfiler extends Log4jEnabledTestCase { + protected final static Logger s_logger = Logger.getLogger(TestProfiler.class); + + private static final long ONE_SECOND = 1000l; + private static final long MILLIS_FACTOR = 1000l; + private static final int MARGIN = 100; + private static final double EXPONENT = 3d; + + @Test + public void testProfilerInMillis() { + s_logger.info("testProfiler() started"); + + final Profiler pf = new Profiler(); + pf.start(); + try { + Thread.sleep(ONE_SECOND); + } catch (final InterruptedException e) { + } + pf.stop(); + + final long durationInMillis = pf.getDurationInMillis(); + s_logger.info("Duration in Millis: " + durationInMillis); + + // An error margin in order to cover the time taken by the star/stop calls. + // 100 milliseconds margin seems too much, but it will avoid assertion error + // and also fail in case a duration in nanoseconds is used instead. + Assert.assertTrue(durationInMillis >= MILLIS_FACTOR && durationInMillis <= MILLIS_FACTOR + MARGIN); + + s_logger.info("testProfiler() stopped"); + } + + @Test + public void testProfilerInNano() { + final Profiler pf = new Profiler(); + pf.start(); + try { + Thread.sleep(ONE_SECOND); + } catch (final InterruptedException e) { + } + pf.stop(); + + final long duration = pf.getDuration(); + s_logger.info("Duration in Nano: " + duration); + Assert.assertTrue(duration >= Math.pow(MILLIS_FACTOR, EXPONENT)); + } + + @Test + public void testProfilerNoStart() { + final Profiler pf = new Profiler(); + try { + Thread.sleep(20); + } catch (final InterruptedException e) { + } + pf.stop(); + + Assert.assertTrue(pf.getDurationInMillis() == -1); + Assert.assertFalse(pf.isStarted()); + } + + @Test + public void testProfilerNoStop() { + final Profiler pf = new Profiler(); + pf.start(); + try { + Thread.sleep(20); + } catch (final InterruptedException e) { + } + + Assert.assertTrue(pf.getDurationInMillis() == -1); + Assert.assertFalse(pf.isStopped()); + } + + @Test + public void testResolution() { + long nanoTime1 = 0l; + long nanoTime2 = 0l; + nanoTime1 = System.nanoTime(); + nanoTime2 = System.nanoTime(); + + // Using sysout here because is faster than the logger and we don't want to + // waste time. + System.out.println("Nano time 1: " + nanoTime1); + System.out.println("Nano time 2: " + nanoTime2); + + // We are measuring the elapsed time in 2 consecutive calls of System.nanoTime() + // That's the same as 0.002 milliseconds or 2000 nanoseconds. + Assert.assertTrue("Expected exactly 2 but it took more than 3 microseconds between 2 consecutive calls to System.nanoTime().", nanoTime2 - nanoTime1 <= 3000); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/UriUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/UriUtilsTest.java b/utils/src/test/java/com/cloud/utils/UriUtilsTest.java new file mode 100644 index 0000000..d2fd997 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/UriUtilsTest.java @@ -0,0 +1,60 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import junit.framework.Assert; + +import org.junit.Test; + +public class UriUtilsTest { + @Test + public void encodeURIComponent() { + Assert.assertEquals("http://localhost", + UriUtils.encodeURIComponent("http://localhost")); + Assert.assertEquals("http://localhost/", + UriUtils.encodeURIComponent("http://localhost/")); + Assert.assertEquals("http://localhost/foo/bar", + UriUtils.encodeURIComponent("http://localhost/foo/bar")); + } + + @Test + public void getUpdateUri() { + // no password param, no request for encryption + Assert.assertEquals("http://localhost/foo/bar?param=true", UriUtils + .getUpdateUri("http://localhost/foo/bar?param=true", false)); + // there is password param but still no request for encryption, should + // be unchanged + Assert.assertEquals("http://localhost/foo/bar?password=1234", UriUtils + .getUpdateUri("http://localhost/foo/bar?password=1234", false)); + // if there is password param and encryption is requested then it may or + // may not be changed depending on how the EncrytionUtils is setup, but + // at least it needs to start with the same url + Assert.assertTrue(UriUtils.getUpdateUri( + "http://localhost/foo/bar?password=1234", true).startsWith( + "http://localhost/foo/bar")); + + //just to see if it is still ok with multiple parameters + Assert.assertEquals("http://localhost/foo/bar?param1=true¶m2=12345", UriUtils + .getUpdateUri("http://localhost/foo/bar?param1=true¶m2=12345", false)); + + //XXX: Interesting cases not covered: + // * port is ignored and left out from the return value + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java b/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java new file mode 100644 index 0000000..2ef6bbd --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/UuidUtilsTest.java @@ -0,0 +1,42 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class UuidUtilsTest { + + @Test + public void testValidateUUIDPass() throws Exception { + String serviceUuid = "f81a9aa3-1f7d-466f-b04b-f2b101486bae"; + + assertTrue(UuidUtils.validateUUID(serviceUuid)); + } + + @Test + public void testValidateUUIDFail() throws Exception { + String serviceUuid = "6fc6ce7-d503-4f95-9e68-c9cd281b13df"; + + assertFalse(UuidUtils.validateUUID(serviceUuid)); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java b/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java new file mode 100644 index 0000000..d397511 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/backoff/impl/ConstantTimeBackoffTest.java @@ -0,0 +1,112 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.backoff.impl; + +import java.util.HashMap; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Test; + +public class ConstantTimeBackoffTest { + final static private Log LOG = LogFactory.getLog(ConstantTimeBackoffTest.class); + + @Test + public void waitBeforeRetryWithInterrupt() throws InterruptedException { + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + backoff.setTimeToWait(10); + Assert.assertTrue(backoff.getWaiters().isEmpty()); + Thread waitThread = new Thread(new Runnable() { + @Override + public void run() { + backoff.waitBeforeRetry(); + } + }); + waitThread.start(); + Thread.sleep(100); + Assert.assertFalse(backoff.getWaiters().isEmpty()); + waitThread.interrupt(); + Thread.sleep(100); + Assert.assertTrue(backoff.getWaiters().isEmpty()); + } + + @Test + public void waitBeforeRetry() throws InterruptedException { + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + // let's not wait too much in a test + backoff.setTimeToWait(0); + // check if the list of waiters is empty + Assert.assertTrue(backoff.getWaiters().isEmpty()); + // call the waitBeforeRetry which will wait 0 ms and return + backoff.waitBeforeRetry(); + // on normal exit the list of waiters should be cleared + Assert.assertTrue(backoff.getWaiters().isEmpty()); + } + + @Test + public void configureEmpty() { + // at this point this is the only way rhe configure method gets invoked, + // therefore have to make sure it works correctly + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + backoff.configure("foo", new HashMap<String, Object>()); + Assert.assertEquals(5000, backoff.getTimeToWait()); + } + + @Test + public void configureWithValue() { + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + HashMap<String, Object> params = new HashMap<String, Object>(); + params.put("seconds", "100"); + backoff.configure("foo", params); + Assert.assertEquals(100000, backoff.getTimeToWait()); + } + + /** + * Test that wakeup returns false when trying to wake a non existing thread. + */ + @Test + public void wakeupNotExisting() { + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + Assert.assertFalse(backoff.wakeup("NOT EXISTING THREAD")); + } + + /** + * Test that wakeup will return true if the thread is waiting. + */ + @Test + public void wakeupExisting() throws InterruptedException { + final ConstantTimeBackoff backoff = new ConstantTimeBackoff(); + backoff.setTimeToWait(10); + Thread thread = new Thread(new Runnable() { + @Override + public void run() { + LOG.debug("before"); + backoff.waitBeforeRetry(); + LOG.debug("after"); + } + }); + thread.start(); + LOG.debug("thread started"); + Thread.sleep(100); + LOG.debug("testing wakeup"); + Assert.assertTrue(backoff.wakeup(thread.getName())); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java b/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java new file mode 100644 index 0000000..0f3f058 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/crypto/EncryptionSecretKeyCheckerTest.java @@ -0,0 +1,45 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.crypto; + +import java.io.IOException; +import java.net.URISyntaxException; +import java.util.Properties; + +import org.junit.Assert; +import org.junit.Test; + +import com.cloud.utils.crypt.EncryptionSecretKeyChecker; +import com.cloud.utils.db.DbProperties; +import com.cloud.utils.exception.CloudRuntimeException; + +public class EncryptionSecretKeyCheckerTest { + + private EncryptionSecretKeyChecker checker = new EncryptionSecretKeyChecker(); + + @Test(expected = CloudRuntimeException.class) + public void testKeyFileDoesNotExists() throws IOException, URISyntaxException { + Assert.assertNotNull(checker); + Properties properties = DbProperties.getDbProperties(); + properties.setProperty("db.cloud.encryption.type", "file"); + checker.check(properties); + } + +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java b/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java new file mode 100644 index 0000000..27d9d50 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/crypto/RSAHelperTest.java @@ -0,0 +1,54 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.crypto; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import org.junit.Test; + +import com.cloud.utils.crypt.RSAHelper; + +public class RSAHelperTest { + @Test + public void testEncryptWithRSA() { + String rsaKey = + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW" + + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk" + + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P" + + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX"; + String encryptedString = RSAHelper.encryptWithSSHPublicKey(rsaKey, "content"); + assertNotNull(encryptedString); + } + + @Test + public void testEncryptWithDSA() { + String dssKey = + "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV" + + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO" + + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA" + + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF" + + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD" + + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR" + + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ=="; + String encryptedString = RSAHelper.encryptWithSSHPublicKey(dssKey, "content"); + assertNull(encryptedString); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java b/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java new file mode 100644 index 0000000..3d4dfc9 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/encoding/UrlEncoderTest.java @@ -0,0 +1,33 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.encoding; + +import org.junit.Assert; +import org.junit.Test; + +public class UrlEncoderTest { + @Test + public void encode() { + Assert.assertEquals("%2Ftmp%2F", new URLEncoder().encode("/tmp/")); + Assert.assertEquals("%20", new URLEncoder().encode(" ")); + Assert.assertEquals("%5F", new URLEncoder().encode("_")); + Assert.assertEquals("%25", new URLEncoder().encode("%")); + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java b/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java new file mode 100644 index 0000000..9e1948e --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/exception/ExceptionUtilTest.java @@ -0,0 +1,52 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.exception; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.io.FileNotFoundException; +import java.io.IOException; + +import org.junit.Test; + +public class ExceptionUtilTest { + + @Test + public void test() throws Exception { + FileNotFoundException fnfe = new FileNotFoundException(); + try { + ExceptionUtil.rethrow(fnfe, IOException.class); + fail(); + } catch (IOException e) { + assertTrue("we won !?!", true); + } + + ExceptionUtil.rethrow(fnfe, ClassNotFoundException.class); + + try { + ExceptionUtil.rethrow(fnfe, FileNotFoundException.class); + fail(); + } catch (FileNotFoundException e) { + assertTrue("we won !?!", true); + } + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java b/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java new file mode 100644 index 0000000..79ff238 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/net/Ip4AddressTest.java @@ -0,0 +1,40 @@ +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +package com.cloud.utils.net; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +public class Ip4AddressTest { + + @Test + public void testEquals() throws Exception { + new EqualsTester() + .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:02"), new Ip4Address(1L, 2L)) + .addEqualityGroup(new Ip4Address("0.0.0.1", "00:00:00:00:00:00"), new Ip4Address(1L, 0L), new Ip4Address(1L, 0L), new Ip4Address(1L), new Ip4Address("0.0.0.1")) + .testEquals(); + } + + @Test + public void testIsSameAddressAs() { + Assert.assertTrue("1 and one should be considdered the same address", new Ip4Address(1L, 5L).isSameAddressAs("0.0.0.1")); + Assert.assertFalse("zero and 0L should be considdered the same address but a Long won't be accepted", new Ip4Address("0.0.0.0", "00:00:00:00:00:08").isSameAddressAs(0L)); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/IpTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/net/IpTest.java b/utils/src/test/java/com/cloud/utils/net/IpTest.java new file mode 100644 index 0000000..89608f1 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/net/IpTest.java @@ -0,0 +1,63 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.net; + +import static org.junit.Assert.assertEquals; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.common.testing.EqualsTester; + +public class IpTest { + + @Test + public void testUltimate() { + Ip max = new Ip(2L * Integer.MAX_VALUE +1 ); + assertEquals("Maximal address not created", "255.255.255.255", max.addr()); + } + @Test + public void testTurningOfTheCentury() { + Ip eve = new Ip(Integer.MAX_VALUE); + assertEquals("Minimal address not created", "127.255.255.255", eve.addr()); + Ip dawn = new Ip(Integer.MAX_VALUE + 1L); + assertEquals("Minimal address not created", "128.0.0.0", dawn.addr()); + } + @Test + public void testStart() { + Ip min = new Ip(0); + assertEquals("Minimal address not created", "0.0.0.0", min.addr()); + } + + @Test + public void testEquals() { + new EqualsTester() + .addEqualityGroup(new Ip("0.0.0.1"), new Ip(1L)) + .addEqualityGroup(new Ip("0.0.0.0"), new Ip(0L)) + .testEquals(); + } + + @Test + public void testIsSameAddressAs() { + Assert.assertTrue("1 and one should be considdered the same address", new Ip(1L).isSameAddressAs("0.0.0.1")); + Assert.assertTrue("zero and 0L should be considdered the same address", new Ip("0.0.0.0").isSameAddressAs(0L)); + } + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java b/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java new file mode 100644 index 0000000..845a435 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/net/MacAddressTest.java @@ -0,0 +1,60 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.net; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class MacAddressTest { + + @Test + public final void testMacAddress() throws Exception { + MacAddress mac = new MacAddress(); + assertEquals(0L,mac.toLong()); + } + + @Test + public final void testMacAddressLong() throws Exception { + MacAddress mac = new MacAddress(1L); + assertEquals(1L,mac.toLong()); + } + + @Test + public final void testMacAddressToLong() throws Exception { + // TODO this test should fail this address is beyond the acceptable range for macaddresses + MacAddress mac = new MacAddress(Long.MAX_VALUE); + assertEquals(Long.MAX_VALUE,mac.toLong()); + System.out.println(mac.toString()); + } + + // TODO public final void testToLong() throws Exception { + // TODO public final void testToByteArray() throws Exception { + // TODO public final void testToStringString() throws Exception { + // TODO public final void testToString() throws Exception { + // TODO public final void testGetMacAddress() throws Exception { + // TODO public final void testParse() throws Exception { + // TODO public final void testMain() throws Exception { + // TODO public final void testParseLong() throws Exception { + // TODO public final void testParseInt() throws Exception { + // TODO public final void testParseShort() throws Exception { + // TODO public final void testParseByte() throws Exception { + +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java new file mode 100644 index 0000000..1ab4459 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/net/NetUtilsTest.java @@ -0,0 +1,421 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.net; + +import static org.hamcrest.Matchers.anyOf; +import static org.hamcrest.Matchers.contains; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.greaterThanOrEqualTo; +import static org.hamcrest.Matchers.lessThanOrEqualTo; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; + +import java.math.BigInteger; +import java.util.SortedSet; +import java.util.TreeSet; + +import org.apache.log4j.Logger; +import org.junit.Test; + +import com.googlecode.ipv6.IPv6Address; + +public class NetUtilsTest { + + private static final Logger s_logger = Logger.getLogger(NetUtilsTest.class); + + @Test + public void testGetRandomIpFromCidrWithSize24() throws Exception { + final String cidr = "192.168.124.1"; + final int size = 24; + final int netCharacters = 12; + + final long ip = NetUtils.getRandomIpFromCidr(cidr, size, new TreeSet<Long>()); + + assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip) + .substring(0, netCharacters))); + } + + @Test + public void testGetRandomIpFromCidrWithSize16() throws Exception { + final String cidr = "192.168.124.1"; + final int size = 16; + final int netCharacters = 8; + + final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>()); + + assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip) + .substring(0, netCharacters))); + } + + @Test + public void testGetRandomIpFromCidrWithSize8() throws Exception { + final String cidr = "192.168.124.1"; + final int size = 8; + final int netCharacters = 4; + + final long ip = NetUtils.getRandomIpFromCidr(cidr, 16, new TreeSet<Long>()); + + assertThat("The ip " + NetUtils.long2Ip(ip) + " retrieved must be within the cidr " + cidr + "/" + size, cidr.substring(0, netCharacters), equalTo(NetUtils.long2Ip(ip) + .substring(0, netCharacters))); + } + + @Test + public void testGetRandomIpFromCidrUsignAvoid() throws Exception { + final String cidr = "192.168.124.1"; + final int size = 30; + + final SortedSet<Long> avoid = new TreeSet<Long>(); + long ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid); + assertThat("We should be able to retrieve an ip on the first call.", ip, not(equalTo(-1L))); + avoid.add(ip); + ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid); + assertThat("We should be able to retrieve an ip on the second call.", ip, not(equalTo(-1L))); + assertThat("ip returned is not in the avoid list", avoid, not(contains(ip))); + avoid.add(ip); + ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid); + assertThat("We should be able to retrieve an ip on the third call.", ip, not(equalTo(-1L))); + assertThat("ip returned is not in the avoid list", avoid, not(contains(ip))); + avoid.add(ip); + ip = NetUtils.getRandomIpFromCidr(cidr, size, avoid); + assertEquals("This should be -1 because we ran out of ip addresses: " + ip, ip, -1); + } + + @Test + public void testIsValidS2SVpnPolicy() { + assertTrue(NetUtils.isValidS2SVpnPolicy("aes128-sha1")); + assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1")); + assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes256-sha1")); + assertTrue(NetUtils.isValidS2SVpnPolicy("3des-md5;modp1024")); + assertTrue(NetUtils.isValidS2SVpnPolicy("3des-sha1,aes128-sha1;modp1536")); + assertFalse(NetUtils.isValidS2SVpnPolicy("des-md5;modp1024,aes128-sha1;modp1536")); + assertFalse(NetUtils.isValidS2SVpnPolicy("des-sha1")); + assertFalse(NetUtils.isValidS2SVpnPolicy("abc-123,ase-sha1")); + assertFalse(NetUtils.isValidS2SVpnPolicy("de-sh,aes-sha1")); + assertFalse(NetUtils.isValidS2SVpnPolicy("")); + assertFalse(NetUtils.isValidS2SVpnPolicy(";modp1536")); + assertFalse(NetUtils.isValidS2SVpnPolicy(",aes;modp1536,,,")); + } + + @Test + public void testGetIp6FromRange() { + assertEquals(NetUtils.getIp6FromRange("1234:5678::1-1234:5678::1"), "1234:5678::1"); + for (int i = 0; i < 5; i++) { + final String ip = NetUtils.getIp6FromRange("1234:5678::1-1234:5678::2"); + assertThat(ip, anyOf(equalTo("1234:5678::1"), equalTo("1234:5678::2"))); + s_logger.info("IP is " + ip); + } + String ipString = null; + final IPv6Address ipStart = IPv6Address.fromString("1234:5678::1"); + final IPv6Address ipEnd = IPv6Address.fromString("1234:5678::ffff:ffff:ffff:ffff"); + for (int i = 0; i < 10; i++) { + ipString = NetUtils.getIp6FromRange(ipStart.toString() + "-" + ipEnd.toString()); + s_logger.info("IP is " + ipString); + final IPv6Address ip = IPv6Address.fromString(ipString); + assertThat(ip, greaterThanOrEqualTo(ipStart)); + assertThat(ip, lessThanOrEqualTo(ipEnd)); + } + } + + @Test + public void testCountIp6InRange() { + assertEquals(new BigInteger("2"), NetUtils.countIp6InRange("1234:5678::1-1234:5678::2")); + } + + @Test + public void testCountIp6InRangeWithInvalidRange() { + assertEquals(null, NetUtils.countIp6InRange("1234:5678::2-1234:5678::0")); + } + + @Test + public void testCountIp6InRangeWithNullStart() { + assertEquals(null, NetUtils.countIp6InRange("-1234:5678::0")); + } + + @Test + public void testCountIp6InRangeWithNoEnd() { + assertEquals(new BigInteger("1"), NetUtils.countIp6InRange("1234:5678::2")); + } + + @Test + public void testGetIp6CidrSize() { + assertEquals(NetUtils.getIp6CidrSize("1234:5678::1/32"), 32); + assertEquals(NetUtils.getIp6CidrSize("1234:5678::1"), 0); + } + + @Test + public void testIsValidIp6Cidr() { + assertTrue(NetUtils.isValidIp6Cidr("1234:5678::1/64")); + assertFalse(NetUtils.isValidIp6Cidr("1234:5678::1")); + } + + @Test + public void testIsValidIpv6() { + assertTrue(NetUtils.isValidIpv6("fc00::1")); + assertFalse(NetUtils.isValidIpv6("")); + assertFalse(NetUtils.isValidIpv6(null)); + assertFalse(NetUtils.isValidIpv6("1234:5678::1/64")); + } + + @Test + public void testIsIp6InRange() { + assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::1-1234:5678:abcd::1")); + assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678:abcd::2-1234:5678:abcd::1")); + assertFalse(NetUtils.isIp6InRange("1234:5678:abcd::1", null)); + assertTrue(NetUtils.isIp6InRange("1234:5678:abcd::1", "1234:5678::1-1234:5679::1")); + } + + @Test + public void testIsIp6InNetwork() { + assertFalse(NetUtils.isIp6InNetwork("1234:5678:abcd::1", "1234:5678::/64")); + assertTrue(NetUtils.isIp6InNetwork("1234:5678::1", "1234:5678::/64")); + assertTrue(NetUtils.isIp6InNetwork("1234:5678::ffff:ffff:ffff:ffff", "1234:5678::/64")); + assertTrue(NetUtils.isIp6InNetwork("1234:5678::", "1234:5678::/64")); + } + + @Test + public void testGetNextIp6InRange() { + String range = "1234:5678::1-1234:5678::8000:0000"; + assertEquals(NetUtils.getNextIp6InRange("1234:5678::8000:0", range), "1234:5678::1"); + assertEquals(NetUtils.getNextIp6InRange("1234:5678::7fff:ffff", range), "1234:5678::8000:0"); + assertEquals(NetUtils.getNextIp6InRange("1234:5678::1", range), "1234:5678::2"); + range = "1234:5678::1-1234:5678::ffff:ffff:ffff:ffff"; + assertEquals(NetUtils.getNextIp6InRange("1234:5678::ffff:ffff:ffff:ffff", range), "1234:5678::1"); + } + + @Test + public void testIsIp6RangeOverlap() { + assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678:1::1-1234:5678:1::ffff")); + assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::1-1234:5678::ffff", "1234:5678::2-1234:5678::f")); + assertTrue(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::f")); + assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::ffff", "1234:5678::2-1234:5678::e")); + assertFalse(NetUtils.isIp6RangeOverlap("1234:5678::f-1234:5678::f", "1234:5678::2-1234:5678::e")); + } + + @Test + public void testStandardizeIp6Address() { + assertEquals(NetUtils.standardizeIp6Address("1234:0000:0000:5678:0000:0000:ABCD:0001"), "1234::5678:0:0:abcd:1"); + assertEquals(NetUtils.standardizeIp6Cidr("1234:0000:0000:5678:0000:0000:ABCD:0001/64"), "1234:0:0:5678::/64"); + } + + @Test + public void testGenerateUriForPvlan() { + assertEquals("pvlan://123-i456", NetUtils.generateUriForPvlan("123", "456").toString()); + } + + @Test + public void testGetPrimaryPvlanFromUri() { + assertEquals("123", NetUtils.getPrimaryPvlanFromUri(NetUtils.generateUriForPvlan("123", "456"))); + } + + @Test + public void testGetIsolatedPvlanFromUri() { + assertEquals("456", NetUtils.getIsolatedPvlanFromUri(NetUtils.generateUriForPvlan("123", "456"))); + } + + @Test + public void testIsValidCIDR() throws Exception { + //Test to check IP Range of 2 CIDR + final String cidrFirst = "10.0.144.0/20"; + final String cidrSecond = "10.0.151.0/20"; + final String cidrThird = "10.0.144.0/21"; + + assertTrue(NetUtils.isValidCIDR(cidrFirst)); + assertTrue(NetUtils.isValidCIDR(cidrSecond)); + assertTrue(NetUtils.isValidCIDR(cidrThird)); + } + + @Test + public void testIsValidCidrList() throws Exception { + final String cidrFirst = "10.0.144.0/20,1.2.3.4/32,5.6.7.8/24"; + final String cidrSecond = "10.0.151.0/20,129.0.0.0/4"; + final String cidrThird = "10.0.144.0/21"; + + assertTrue(NetUtils.isValidCidrList(cidrFirst)); + assertTrue(NetUtils.isValidCidrList(cidrSecond)); + assertTrue(NetUtils.isValidCidrList(cidrThird)); + } + + @Test + public void testIsSameIpRange() { + final String cidrFirst = "10.0.144.0/20"; + final String cidrSecond = "10.0.151.0/20"; + final String cidrThird = "10.0.144.0/21"; + + //Check for exactly same CIDRs + assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrFirst)); + //Check for 2 different CIDRs, but same IP Range + assertTrue(NetUtils.isSameIpRange(cidrFirst, cidrSecond)); + //Check for 2 different CIDRs and different IP Range + assertFalse(NetUtils.isSameIpRange(cidrFirst, cidrThird)); + //Check for Incorrect format of CIDR + assertFalse(NetUtils.isSameIpRange(cidrFirst, "10.3.6.5/50")); + } + + @Test + public void testGenerateMacOnIncrease() { + String mac = "06:01:23:00:45:67"; + assertEquals("06:01:25:00:45:67", NetUtils.generateMacOnIncrease(mac, 2)); + assertEquals("06:01:33:00:45:67", NetUtils.generateMacOnIncrease(mac, 16)); + mac = "06:ff:ff:00:45:67"; + assertEquals("06:00:00:00:45:67", NetUtils.generateMacOnIncrease(mac, 1)); + assertEquals("06:00:0f:00:45:67", NetUtils.generateMacOnIncrease(mac, 16)); + } + + @Test + public void testGetLocalIPString() { + assertNotNull(NetUtils.getLocalIPString()); + } + + @Test + public void testSameIsolationId() { + assertTrue(NetUtils.isSameIsolationId("1", "vlan://1")); + assertTrue(NetUtils.isSameIsolationId("", null)); + assertTrue(NetUtils.isSameIsolationId("UnTagged", "vlan://uNtAGGED")); + assertFalse(NetUtils.isSameIsolationId("2", "vlan://uNtAGGED")); + assertFalse(NetUtils.isSameIsolationId("2", "vlan://3")); + assertFalse(NetUtils.isSameIsolationId("bla", null)); + } + + @Test + public void testValidateGuestCidr() throws Exception { + final String guestCidr = "192.168.1.0/24"; + + assertTrue(NetUtils.validateGuestCidr(guestCidr)); + } + + @Test + public void testMac2Long() { + assertEquals(0l, NetUtils.mac2Long("00:00:00:00:00:00")); + assertEquals(1l, NetUtils.mac2Long("00:00:00:00:00:01")); + assertEquals(0xFFl, NetUtils.mac2Long("00:00:00:00:00:FF")); + assertEquals(0xFFAAl, NetUtils.mac2Long("00:00:00:00:FF:AA")); + assertEquals(0x11FFAAl, NetUtils.mac2Long("00:00:00:11:FF:AA")); + assertEquals(0x12345678l, NetUtils.mac2Long("00:00:12:34:56:78")); + assertEquals(0x123456789Al, NetUtils.mac2Long("00:12:34:56:78:9A")); + assertEquals(0x123456789ABCl, NetUtils.mac2Long("12:34:56:78:9A:BC")); + } + + @Test + public void testLong2Mac() { + assertEquals("00:00:00:00:00:00", NetUtils.long2Mac(0l)); + assertEquals("00:00:00:00:00:01", NetUtils.long2Mac(1l)); + assertEquals("00:00:00:00:00:ff", NetUtils.long2Mac(0xFFl)); + assertEquals("00:00:00:00:ff:aa", NetUtils.long2Mac(0xFFAAl)); + assertEquals("00:00:00:11:ff:aa", NetUtils.long2Mac(0x11FFAAl)); + assertEquals("00:00:12:34:56:78", NetUtils.long2Mac(0x12345678l)); + assertEquals("00:12:34:56:78:9a", NetUtils.long2Mac(0x123456789Al)); + assertEquals("12:34:56:78:9a:bc", NetUtils.long2Mac(0x123456789ABCl)); + } + + @Test + public void testIp2Long() { + assertEquals(0x7f000001l, NetUtils.ip2Long("127.0.0.1")); + assertEquals(0xc0a80001l, NetUtils.ip2Long("192.168.0.1")); + assertEquals(0x08080808l, NetUtils.ip2Long("8.8.8.8")); + } + + @Test + public void testLong2Ip() { + assertEquals("127.0.0.1", NetUtils.long2Ip(0x7f000001l)); + assertEquals("192.168.0.1", NetUtils.long2Ip(0xc0a80001l)); + assertEquals("8.8.8.8", NetUtils.long2Ip(0x08080808l)); + } + + @Test + public void test31BitPrefixStart() { + final String ipAddress = "192.168.0.0"; + final String cidr = "192.168.0.0/31"; + + final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr); + + assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange); + } + + @Test + public void test31BitPrefixEnd() { + final String ipAddress = "192.168.0.1"; + final String cidr = "192.168.0.0/31"; + + final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr); + + assertTrue("Check if the subnetUtils.setInclusiveHostCount(true) has been called.", isInRange); + } + + @Test + public void test31BitPrefixFail() { + final String ipAddress = "192.168.0.2"; + final String cidr = "192.168.0.0/31"; + + final boolean isInRange = NetUtils.isIpWithtInCidrRange(ipAddress, cidr); + + assertFalse("Out of the range. Why did it return true?", isInRange); + } + + @Test + public void test31BitPrefixIpRangesOverlapd() { + final String gw = "192.168.0.0"; + String ip1; + String ip2; + + for (int i = 1, j = 2; i <= 254; i++, j++) { + ip1 = "192.168.0." + i; + ip2 = "192.168.0." + j; + + final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw); + assertFalse("It should overlap, but it's a 31-bit ip", doesOverlap); + } + } + + @Test + public void test31BitPrefixIpRangesOverlapdFail() { + String gw; + String ip1; + String ip2; + + for (int i = 10, j = 12; i <= 254; i++, j++) { + gw = "192.168.0." + i; + ip1 = "192.168.0." + i; + ip2 = "192.168.0." + j; + + final boolean doesOverlap = NetUtils.ipRangesOverlap(ip1, ip2, gw, gw); + assertTrue("It overlaps!", doesOverlap); + } + } + + @Test + public void testIs31PrefixCidrFail() { + final String cidr = "10.10.0.0/32"; + final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr); + + assertFalse("It should fail! 32 bit prefix.", is31PrefixCidr); + } + + @Test + public void testIs31PrefixCidr() { + final String cidr = "10.10.0.0/31"; + final boolean is31PrefixCidr = NetUtils.is31PrefixCidr(cidr); + + assertTrue("It should pass! 31 bit prefix.", is31PrefixCidr); + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java new file mode 100644 index 0000000..6d58b5b --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/rest/RESTServiceConnectorTest.java @@ -0,0 +1,395 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.rest; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.util.Collections; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.DeleteMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.params.HttpClientParams; +import org.apache.http.HttpStatus; +import org.junit.Before; +import org.junit.Test; + +public class RESTServiceConnectorTest { + protected static final String UUID = "aaaa"; + protected static final String UUID_JSON_RESPONSE = "{\"uuid\" : \"aaaa\"}"; + + RESTServiceConnector connector; + HttpClient client = mock(HttpClient.class); + HttpMethod method; + String type; + String uri; + + @Before + public void setUp() { + final HttpClientParams hmp = mock(HttpClientParams.class); + when(client.getParams()).thenReturn(hmp); + connector = new RESTServiceConnector(null) { + @Override + public HttpClient createHttpClient() { + return client; + } + + @Override + public HttpMethod createMethod(final String newType, final String newUri) { + type = newType; + uri = newUri; + return method; + } + }; + + connector.validation = new RESTValidationStrategy(); + connector.setAdminCredentials("admin", "adminpass"); + connector.setControllerAddress("localhost"); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteLoginWithoutHostname() throws CloudstackRESTException { + connector.setControllerAddress(null); + connector.validation.login(RESTServiceConnector.protocol, client); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteLoginWithoutCredentials() throws CloudstackRESTException { + method = mock(PutMethod.class); + connector.setAdminCredentials(null, null); + connector.validation.login(RESTServiceConnector.protocol, client); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteUpdateObjectWithoutHostname() throws CloudstackRESTException { + method = mock(PutMethod.class); + connector.setControllerAddress(null); + connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteUpdateObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(PutMethod.class); + connector.setAdminCredentials(null, null); + connector.executeUpdateObject(new String(), "/", Collections.<String, String> emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteCreateObjectWithoutHostname() throws CloudstackRESTException { + method = mock(PostMethod.class); + connector.setControllerAddress(null); + connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteCreateObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(PostMethod.class); + connector.setAdminCredentials(null, null); + connector.executeCreateObject(new String(), String.class, "/", Collections.<String, String> emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteDeleteObjectWithoutHostname() throws CloudstackRESTException { + method = mock(DeleteMethod.class); + connector.setControllerAddress(null); + connector.executeDeleteObject("/"); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteDeleteObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(DeleteMethod.class); + connector.setAdminCredentials(null, null); + connector.executeDeleteObject("/"); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRetrieveObjectWithoutHostname() throws CloudstackRESTException { + method = mock(GetMethod.class); + connector.setControllerAddress(null); + connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap()); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRetrieveObjectWithoutCredentials() throws CloudstackRESTException { + method = mock(GetMethod.class); + connector.setAdminCredentials(null, null); + connector.executeRetrieveObject(String.class, "/", Collections.<String, String> emptyMap()); + } + + @Test + public void testExecuteMethod() throws CloudstackRESTException { + final GetMethod gm = mock(GetMethod.class); + + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_OK); + connector.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteMethodWithLogin() throws CloudstackRESTException, HttpException, IOException { + final GetMethod gm = mock(GetMethod.class); + when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); + connector.executeMethod(gm); + verify(gm, times(1)).getStatusCode(); + } + + /* Bit of a roundabout way to ensure that login is called after an un authorized result + * It not possible to properly mock login() + */ + public void testExecuteMethodWithLoginSucced2ndAttempt() throws CloudstackRESTException, HttpException, IOException { + // Prepare + final GetMethod gm = mock(GetMethod.class); + when(gm.getStatusCode()).thenReturn(HttpStatus.SC_UNAUTHORIZED).thenReturn(HttpStatus.SC_UNAUTHORIZED); + + final RESTValidationStrategy previousValidationStrategy = connector.validation; + connector.validation = new RESTValidationStrategy(){ + @Override + protected void login(final String protocol, final HttpClient client) + throws CloudstackRESTException { + // Do nothing + } + }; + connector.setAdminCredentials("admin", "adminpass"); + connector.setControllerAddress("localhost"); + + // Execute + connector.executeMethod(gm); + // Leave mock object as is was + connector.validation = previousValidationStrategy; + + // Assert/verify + verify(gm, times(2)).getStatusCode(); + } + + @Test + public void testExecuteCreateObject() throws CloudstackRESTException, IOException { + JsonEntity ls = new JsonEntity(); + method = mock(PostMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_CREATED); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); + ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap()); + assertTrue(UUID.equals(ls.getUuid())); + verify(method, times(1)).releaseConnection(); + + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteCreateObjectFailure() throws CloudstackRESTException, IOException { + JsonEntity ls = new JsonEntity(); + method = mock(PostMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + final Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(method.getResponseHeader("Content-Type")).thenReturn(header); + when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(method.isRequestSent()).thenReturn(true); + try { + ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteCreateObjectException() throws CloudstackRESTException, IOException { + JsonEntity ls = new JsonEntity(); + when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + method = mock(PostMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + final Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(method.getResponseHeader("Content-Type")).thenReturn(header); + when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + try { + ls = connector.executeCreateObject(ls, JsonEntity.class, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteUpdateObject() throws CloudstackRESTException, IOException { + final JsonEntity ls = new JsonEntity(); + method = mock(PutMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap()); + verify(method, times(1)).releaseConnection(); + verify(client, times(1)).executeMethod(method); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteUpdateObjectFailure() throws CloudstackRESTException, IOException { + final JsonEntity ls = new JsonEntity(); + method = mock(PutMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + final Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(method.getResponseHeader("Content-Type")).thenReturn(header); + when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(method.isRequestSent()).thenReturn(true); + try { + connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteUpdateObjectException() throws CloudstackRESTException, IOException { + final JsonEntity ls = new JsonEntity(); + method = mock(PutMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(client.executeMethod((HttpMethod)any())).thenThrow(new IOException()); + try { + connector.executeUpdateObject(ls, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteDeleteObject() throws CloudstackRESTException, IOException { + method = mock(DeleteMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + connector.executeDeleteObject("/"); + verify(method, times(1)).releaseConnection(); + verify(client, times(1)).executeMethod(method); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteDeleteObjectFailure() throws CloudstackRESTException, IOException { + method = mock(DeleteMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + final Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(method.getResponseHeader("Content-Type")).thenReturn(header); + when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(method.isRequestSent()).thenReturn(true); + try { + connector.executeDeleteObject("/"); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteDeleteObjectException() throws CloudstackRESTException, IOException { + method = mock(DeleteMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_NO_CONTENT); + when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + try { + connector.executeDeleteObject("/"); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test + public void testExecuteRetrieveObject() throws CloudstackRESTException, IOException { + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); + connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap()); + verify(method, times(1)).releaseConnection(); + verify(client, times(1)).executeMethod(method); + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRetrieveObjectFailure() throws CloudstackRESTException, IOException { + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_INTERNAL_SERVER_ERROR); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); + final Header header = mock(Header.class); + when(header.getValue()).thenReturn("text/html"); + when(method.getResponseHeader("Content-Type")).thenReturn(header); + when(method.getResponseBodyAsString()).thenReturn("Off to timbuktu, won't be back later."); + when(method.isRequestSent()).thenReturn(true); + try { + connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + + @Test(expected = CloudstackRESTException.class) + public void testExecuteRetrieveObjectException() throws CloudstackRESTException, IOException { + method = mock(GetMethod.class); + when(method.getStatusCode()).thenReturn(HttpStatus.SC_OK); + when(method.getResponseBodyAsString()).thenReturn(UUID_JSON_RESPONSE); + when(client.executeMethod((HttpMethod)any())).thenThrow(new HttpException()); + try { + connector.executeRetrieveObject(JsonEntity.class, "/", Collections.<String, String> emptyMap()); + } finally { + verify(method, times(1)).releaseConnection(); + } + } + +} + +class JsonEntity { + private String displayName; + private String uuid; + private String href; + private String schema; + + public String getDisplayName() { + return displayName; + } + + public void setDisplayName(final String displayName) { + this.displayName = displayName; + } + + public String getUuid() { + return uuid; + } + + public void setUuid(final String uuid) { + this.uuid = uuid; + } + + public String getHref() { + return href; + } + + public void setHref(final String href) { + this.href = href; + } + + public String getSchema() { + return schema; + } + + public void setSchema(final String schema) { + this.schema = schema; + } +} \ No newline at end of file http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java b/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java new file mode 100644 index 0000000..a3daf91 --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/ssh/SSHKeysHelperTest.java @@ -0,0 +1,73 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.ssh; + +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class SSHKeysHelperTest { + @Test + public void rsaKeyTest() { + String rsaKey = + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW" + + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk" + + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P" + + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX test@testkey"; + String storedRsaKey = + "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC2D2Cs0XAEqm+ajJpumIPrMpKp0CWtIW+8ZY2/MJCW" + + "hge1eY18u9I3PPnkMVJsTOaN0wQojjw4AkKgKjNZXA9wyUq56UyN/stmipu8zifWPgxQGDRkuzzZ6buk" + + "ef8q2Awjpo8hv5/0SRPJxQLEafESnUP+Uu/LUwk5VVC7PHzywJRUGFuzDl/uT72+6hqpL2YpC6aTl4/P" + + "2eDvUQhCdL9dBmUSFX8ftT53W1jhsaQl7mPElVgSCtWz3IyRkogobMPrpJW/IPKEiojKIuvNoNv4CDR6" + "ybeVjHOJMb9wi62rXo+CzUsW0Y4jPOX/OykAm5vrNOhQhw0aaBcv5XVv8BRX"; + String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(rsaKey); + String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey); + + assertTrue(storedRsaKey.equals(parsedKey)); + assertTrue("f6:96:3f:f4:78:f7:80:11:6c:f8:e3:2b:40:20:f1:14".equals(fingerprint)); + + } + + @Test + public void dsaKeyTest() { + String dssKey = + "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV" + + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO" + + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA" + + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF" + + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD" + + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR" + + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ== test key"; + String storedDssKey = + "ssh-dss AAAAB3NzaC1kc3MAAACBALbaewDnzZ5AcGbZno7VW1m7Si3Q+yEANXZioVupfSwOP0q9aP2iV" + + "tyqq575JnUVZXMDR2Gr254F/qCJ0TKAvucN0gcd2XslX4jBcu1Z7s7YZf6d7fC58k0NE6/keokJNKhQO" + + "i56iirRzSA/YFrD64mzfq6rEmai0q7GjGGP0RT1AAAAFQDO5++6JonyqnoRkV9Yl1OaEOPjVwAAAIAYA" + + "tqtKtU/INlTIuL3wt3nyKzwPUnz3fqxP5Ger3OlRZsOahalTFt2OF5jGGmCunyBTRteOetZObr0QhUIF" + + "4bSDr6UiYYYbH1ES0ws/t1mDIeTh3UUHV1QYACN6c07FKyKLMtB9AthiG2FMLKCEedG3NeXItuNzsuQD" + + "+n/K1rzMAAAAIBi5SM4pFPiB7BvTZvARV56vrG5QNgWVazSwbwgl/EACiWYbRauHDUQA9f+Rq+ayWcsR" + + "os1CD+Q81y9SmlQaZVKkSPZLxXfu5bi3s4o431xjilhZdt4vKbj2pK364IjghJPNBBfmRXzlj9awKxr/" + "UebZcBgNRyeky7VZSbbF2jQSQ=="; + String parsedKey = SSHKeysHelper.getPublicKeyFromKeyMaterial(dssKey); + String fingerprint = SSHKeysHelper.getPublicKeyFingerprint(parsedKey); + + assertTrue(storedDssKey.equals(parsedKey)); + assertTrue("fc:6e:ef:31:93:f8:92:2b:a9:03:c7:06:90:f5:ec:bb".equals(fingerprint)); + + } +} http://git-wip-us.apache.org/repos/asf/cloudstack/blob/83fd8f60/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java ---------------------------------------------------------------------- diff --git a/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java b/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java new file mode 100644 index 0000000..51cde2c --- /dev/null +++ b/utils/src/test/java/com/cloud/utils/testcase/Log4jEnabledTestCase.java @@ -0,0 +1,58 @@ +// +// Licensed to the Apache Software Foundation (ASF) under one +// or more contributor license agreements. See the NOTICE file +// distributed with this work for additional information +// regarding copyright ownership. The ASF licenses this file +// to you under the Apache License, Version 2.0 (the +// "License"); you may not use this file except in compliance +// with the License. You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, +// software distributed under the License is distributed on an +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +// KIND, either express or implied. See the License for the +// specific language governing permissions and limitations +// under the License. +// + +package com.cloud.utils.testcase; + +import java.io.File; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Random; + +import junit.framework.TestCase; + +import org.apache.log4j.xml.DOMConfigurator; + +public class Log4jEnabledTestCase extends TestCase { + @Override + protected void setUp() { + URL configUrl = System.class.getResource("/conf/log4j-cloud.xml"); + if (configUrl != null) { + System.out.println("Configure log4j using log4j-cloud.xml"); + + try { + File file = new File(configUrl.toURI()); + + System.out.println("Log4j configuration from : " + file.getAbsolutePath()); + DOMConfigurator.configureAndWatch(file.getAbsolutePath(), 10000); + } catch (URISyntaxException e) { + System.out.println("Unable to convert log4j configuration Url to URI"); + } + } else { + System.out.println("Configure log4j with default properties"); + } + } + + public static int getRandomMilliseconds(int rangeLo, int rangeHi) { + int i = new Random().nextInt(); + + long pos = (long)i - (long)Integer.MIN_VALUE; + long iRange = (long)Integer.MAX_VALUE - (long)Integer.MIN_VALUE; + return rangeLo + (int)((rangeHi - rangeLo) * pos / iRange); + } +}