You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@toree.apache.org by lb...@apache.org on 2016/01/22 23:07:20 UTC
[12/51] [abbrv] incubator-toree git commit: Moved scala files to new
locations based on new package
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommCloseHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommCloseHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommCloseHandlerSpec.scala
new file mode 100644
index 0000000..49582f8
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommCloseHandlerSpec.scala
@@ -0,0 +1,155 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import java.util.UUID
+
+import akka.actor.{Props, ActorRef, ActorSystem}
+import akka.testkit.{TestProbe, ImplicitSender, TestKit}
+import com.ibm.spark.kernel.protocol.v5
+import com.ibm.spark.kernel.protocol.v5.content.{ClearOutput, CommClose}
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import com.ibm.spark.kernel.protocol.v5.{KernelMessage, SystemActorType, KMBuilder}
+import com.ibm.spark.comm.{CommRegistrar, CommWriter, CommCallbacks, CommStorage}
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{BeforeAndAfter, FunSpecLike, Matchers}
+import org.mockito.Mockito._
+import org.mockito.Matchers._
+
+import scala.concurrent.duration._
+
+class CommCloseHandlerSpec extends TestKit(
+ ActorSystem("CommCloseHandlerSpec")
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+ with BeforeAndAfter
+{
+ private val TestCommId = UUID.randomUUID().toString
+ private val TestTargetName = "some test target"
+
+ private var kmBuilder: KMBuilder = _
+ private var spyCommStorage: CommStorage = _
+ private var mockCommCallbacks: CommCallbacks = _
+ private var mockCommRegistrar: CommRegistrar = _
+ private var mockActorLoader: ActorLoader = _
+ private var commCloseHandler: ActorRef = _
+ private var kernelMessageRelayProbe: TestProbe = _
+ private var statusDispatchProbe: TestProbe = _
+
+ before {
+ kmBuilder = KMBuilder()
+ mockCommCallbacks = mock[CommCallbacks]
+ spyCommStorage = spy(new CommStorage())
+ mockCommRegistrar = mock[CommRegistrar]
+
+ mockActorLoader = mock[ActorLoader]
+
+ commCloseHandler = system.actorOf(Props(
+ classOf[CommCloseHandler],
+ mockActorLoader, mockCommRegistrar, spyCommStorage
+ ))
+
+ // Used to intercept responses
+ kernelMessageRelayProbe = TestProbe()
+ when(mockActorLoader.load(SystemActorType.KernelMessageRelay))
+ .thenReturn(system.actorSelection(kernelMessageRelayProbe.ref.path.toString))
+
+ // Used to intercept busy/idle messages
+ statusDispatchProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.StatusDispatch))
+ .thenReturn(system.actorSelection(statusDispatchProbe.ref.path.toString))
+ }
+
+ describe("CommCloseHandler") {
+ describe("#process") {
+ it("should execute close callbacks if the id is registered") {
+ // Mark our id as registered
+ doReturn(Some(mockCommCallbacks)).when(spyCommStorage)
+ .getCommIdCallbacks(TestCommId)
+
+ // Send a comm_open message with the test target
+ commCloseHandler ! kmBuilder
+ .withHeader(CommClose.toTypeString)
+ .withContentString(CommClose(TestCommId, v5.MsgData.Empty))
+ .build
+
+ // Should receive a busy and an idle message
+ statusDispatchProbe.receiveN(2, 200.milliseconds)
+
+ // Verify that the msg callbacks were triggered along the way
+ verify(mockCommCallbacks).executeCloseCallbacks(
+ any[CommWriter], any[v5.UUID], any[v5.MsgData])
+ }
+
+ it("should not execute close callbacks if the id is not registered") {
+ // Mark our target as not registered
+ doReturn(None).when(spyCommStorage).getCommIdCallbacks(TestCommId)
+
+ // Send a comm_msg message with the test id
+ commCloseHandler ! kmBuilder
+ .withHeader(CommClose.toTypeString)
+ .withContentString(CommClose(TestCommId, v5.MsgData.Empty))
+ .build
+
+ // Should receive a busy and an idle message
+ statusDispatchProbe.receiveN(2, 200.milliseconds)
+
+ // Verify that the msg callbacks were NOT triggered along the way
+ verify(mockCommCallbacks, never()).executeCloseCallbacks(
+ any[CommWriter], any[v5.UUID], any[v5.MsgData])
+ }
+
+ it("should do nothing if there is a parsing error") {
+ // Send a comm_open message with an invalid content string
+ commCloseHandler ! kmBuilder
+ .withHeader(CommClose.toTypeString)
+ .withContentString(ClearOutput(_wait = true))
+ .build
+
+ // TODO: Is there a better way to test for this without an upper time
+ // limit? Is there a different logical approach?
+ kernelMessageRelayProbe.expectNoMsg(200.milliseconds)
+ }
+
+ it("should include the parent's header in the parent header of " +
+ "outgoing messages"){
+
+ // Register a callback that sends a message using the comm writer
+ val closeCallback: CommCallbacks.CloseCallback =
+ new CommCallbacks.CloseCallback() {
+ def apply(v1: CommWriter, v2: v5.UUID, v4: v5.MsgData) =
+ v1.writeMsg(v5.MsgData.Empty)
+ }
+ val callbacks = (new CommCallbacks).addCloseCallback(closeCallback)
+ doReturn(Some(callbacks)).when(spyCommStorage)
+ .getCommIdCallbacks(TestCommId)
+
+ // Send a comm close message
+ val msg = kmBuilder
+ .withHeader(CommClose.toTypeString)
+ .withContentString(CommClose(TestCommId, v5.MsgData.Empty))
+ .build
+ commCloseHandler ! msg
+
+ // Verify that the message sent by the handler has the desired property
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, _, parentHeader, _, _) =>
+ parentHeader == msg.header
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommMsgHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommMsgHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommMsgHandlerSpec.scala
new file mode 100644
index 0000000..582a08e
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommMsgHandlerSpec.scala
@@ -0,0 +1,153 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import java.util.UUID
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import com.ibm.spark.kernel.protocol.v5
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.comm._
+import com.ibm.spark.kernel.protocol.v5.content.{CommMsg, ClearOutput, CommOpen}
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{BeforeAndAfter, FunSpecLike, Matchers}
+
+import scala.concurrent.duration._
+
+class CommMsgHandlerSpec extends TestKit(
+ ActorSystem("CommMsgHandlerSpec")
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+ with BeforeAndAfter
+{
+ private val TestCommId = UUID.randomUUID().toString
+ private val TestTargetName = "some test target"
+
+ private var kmBuilder: KMBuilder = _
+ private var spyCommStorage: CommStorage = _
+ private var mockCommCallbacks: CommCallbacks = _
+ private var mockActorLoader: ActorLoader = _
+ private var commMsgHandler: ActorRef = _
+ private var kernelMessageRelayProbe: TestProbe = _
+ private var statusDispatchProbe: TestProbe = _
+
+ before {
+ kmBuilder = KMBuilder()
+ mockCommCallbacks = mock[CommCallbacks]
+ spyCommStorage = spy(new CommStorage())
+
+ mockActorLoader = mock[ActorLoader]
+
+ commMsgHandler = system.actorOf(Props(
+ classOf[CommMsgHandler],
+ mockActorLoader, mock[CommRegistrar], spyCommStorage
+ ))
+
+ // Used to intercept responses
+ kernelMessageRelayProbe = TestProbe()
+ when(mockActorLoader.load(SystemActorType.KernelMessageRelay))
+ .thenReturn(system.actorSelection(kernelMessageRelayProbe.ref.path.toString))
+
+ // Used to intercept busy/idle messages
+ statusDispatchProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.StatusDispatch))
+ .thenReturn(system.actorSelection(statusDispatchProbe.ref.path.toString))
+ }
+
+ describe("CommMsgHandler") {
+ describe("#process") {
+ it("should execute msg callbacks if the id is registered") {
+ // Mark our id as registered
+ doReturn(Some(mockCommCallbacks)).when(spyCommStorage)
+ .getCommIdCallbacks(TestCommId)
+
+ // Send a comm_open message with the test target
+ commMsgHandler ! kmBuilder
+ .withHeader(CommMsg.toTypeString)
+ .withContentString(CommMsg(TestCommId, v5.MsgData.Empty))
+ .build
+
+ // Should receive a busy and an idle message
+ statusDispatchProbe.receiveN(2, 200.milliseconds)
+
+ // Verify that the msg callbacks were triggered along the way
+ verify(mockCommCallbacks).executeMsgCallbacks(
+ any[CommWriter], any[v5.UUID], any[v5.MsgData])
+ }
+
+ it("should not execute msg callbacks if the id is not registered") {
+ // Mark our target as not registered
+ doReturn(None).when(spyCommStorage).getCommIdCallbacks(TestCommId)
+
+ // Send a comm_msg message with the test id
+ commMsgHandler ! kmBuilder
+ .withHeader(CommMsg.toTypeString)
+ .withContentString(CommMsg(TestCommId, v5.MsgData.Empty))
+ .build
+
+ // Should receive a busy and an idle message
+ statusDispatchProbe.receiveN(2, 200.milliseconds)
+
+ // Verify that the msg callbacks were NOT triggered along the way
+ verify(mockCommCallbacks, never()).executeMsgCallbacks(
+ any[CommWriter], any[v5.UUID], any[v5.MsgData])
+ }
+
+ it("should do nothing if there is a parsing error") {
+ // Send a comm_open message with an invalid content string
+ commMsgHandler ! kmBuilder
+ .withHeader(CommMsg.toTypeString)
+ .withContentString(ClearOutput(_wait = true))
+ .build
+
+ // TODO: Is there a better way to test for this without an upper time
+ // limit? Is there a different logical approach?
+ kernelMessageRelayProbe.expectNoMsg(200.milliseconds)
+ }
+
+ it("should include the parent's header in the parent header of " +
+ "outgoing messages"){
+
+ // Register a callback that sends a message using the comm writer
+ val msgCallback: CommCallbacks.MsgCallback =
+ new CommCallbacks.MsgCallback() {
+ def apply(v1: CommWriter, v2: v5.UUID, v3: v5.MsgData): Unit =
+ v1.writeMsg(MsgData.Empty)
+ }
+ val callbacks = (new CommCallbacks).addMsgCallback(msgCallback)
+ doReturn(Some(callbacks)).when(spyCommStorage)
+ .getCommIdCallbacks(TestCommId)
+
+ // Send a comm_msg message with the test id
+ val msg = kmBuilder
+ .withHeader(CommMsg.toTypeString)
+ .withContentString(CommMsg(TestCommId, v5.MsgData.Empty))
+ .build
+ commMsgHandler ! msg
+
+ // Verify that the message sent by the handler has the desired property
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, _, parentHeader, _, _) =>
+ parentHeader == msg.header
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommOpenHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommOpenHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommOpenHandlerSpec.scala
new file mode 100644
index 0000000..64013e9
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/CommOpenHandlerSpec.scala
@@ -0,0 +1,157 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import java.util.UUID
+
+import com.ibm.spark.kernel.protocol.v5
+
+import akka.actor.{Props, ActorRef, ActorSystem}
+import akka.testkit.{TestProbe, ImplicitSender, TestKit}
+import com.ibm.spark.kernel.protocol.v5.content.{CommClose, ClearOutput, CommOpen}
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.comm._
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import org.mockito.Mockito._
+import org.mockito.Matchers._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{BeforeAndAfter, FunSpecLike, Matchers}
+
+import scala.concurrent.duration._
+
+class CommOpenHandlerSpec extends TestKit(
+ ActorSystem("CommOpenHandlerSpec")
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+ with BeforeAndAfter
+{
+ private val TestCommId = UUID.randomUUID().toString
+ private val TestTargetName = "some test target"
+
+ private var kmBuilder: KMBuilder = _
+ private var spyCommStorage: CommStorage = _
+ private var mockCommCallbacks: CommCallbacks = _
+ private var mockCommRegistrar: CommRegistrar = _
+ private var mockActorLoader: ActorLoader = _
+ private var commOpenHandler: ActorRef = _
+ private var kernelMessageRelayProbe: TestProbe = _
+ private var statusDispatchProbe: TestProbe = _
+
+ before {
+ kmBuilder = KMBuilder()
+ mockCommCallbacks = mock[CommCallbacks]
+ spyCommStorage = spy(new CommStorage())
+ mockCommRegistrar = mock[CommRegistrar]
+
+ mockActorLoader = mock[ActorLoader]
+
+ commOpenHandler = system.actorOf(Props(
+ classOf[CommOpenHandler],
+ mockActorLoader, mockCommRegistrar, spyCommStorage
+ ))
+
+ // Used to intercept responses
+ kernelMessageRelayProbe = TestProbe()
+ when(mockActorLoader.load(SystemActorType.KernelMessageRelay))
+ .thenReturn(system.actorSelection(kernelMessageRelayProbe.ref.path.toString))
+
+ // Used to intercept busy/idle messages
+ statusDispatchProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.StatusDispatch))
+ .thenReturn(system.actorSelection(statusDispatchProbe.ref.path.toString))
+ }
+
+ describe("CommOpenHandler") {
+ describe("#process") {
+ it("should execute open callbacks if the target exists") {
+ // Mark our target as registered
+ doReturn(Some(mockCommCallbacks)).when(spyCommStorage)
+ .getTargetCallbacks(TestTargetName)
+
+ // Send a comm_open message with the test target
+ commOpenHandler ! kmBuilder
+ .withHeader(CommOpen.toTypeString)
+ .withContentString(CommOpen(TestCommId, TestTargetName, v5.MsgData.Empty))
+ .build
+
+ // Should receive a busy and an idle message
+ statusDispatchProbe.receiveN(2, 200.milliseconds)
+
+ // Verify that the open callbacks were triggered along the way
+ verify(mockCommCallbacks).executeOpenCallbacks(
+ any[CommWriter], any[v5.UUID], anyString(), any[v5.MsgData])
+ }
+
+ it("should close the comm connection if the target does not exist") {
+ // Mark our target as not registered
+ doReturn(None).when(spyCommStorage).getTargetCallbacks(TestTargetName)
+
+ // Send a comm_open message with the test target
+ commOpenHandler ! kmBuilder
+ .withHeader(CommOpen.toTypeString)
+ .withContentString(CommOpen(TestCommId, TestTargetName, v5.MsgData.Empty))
+ .build
+
+ // Should receive a close message as a result of the target missing
+ kernelMessageRelayProbe.expectMsgPF(200.milliseconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ header.msg_type should be (CommClose.toTypeString)
+ }
+ }
+
+ it("should do nothing if there is a parsing error") {
+ // Send a comm_open message with an invalid content string
+ commOpenHandler ! kmBuilder
+ .withHeader(CommOpen.toTypeString)
+ .withContentString(ClearOutput(_wait = true))
+ .build
+
+ // TODO: Is there a better way to test for this without an upper time
+ // limit? Is there a different logical approach?
+ kernelMessageRelayProbe.expectNoMsg(200.milliseconds)
+ }
+
+ it("should include the parent's header in the parent header of " +
+ "outgoing messages"){
+
+ // Register a callback that sends a message using the comm writer
+ val openCallback: CommCallbacks.OpenCallback =
+ new CommCallbacks.OpenCallback() {
+ def apply(v1: CommWriter, v2: v5.UUID, v3: String, v4: v5.MsgData) =
+ v1.writeMsg(MsgData.Empty)
+ }
+ val callbacks = (new CommCallbacks).addOpenCallback(openCallback)
+ doReturn(Some(callbacks)).when(spyCommStorage)
+ .getCommIdCallbacks(TestCommId)
+
+ // Send a comm_open message
+ val msg = kmBuilder
+ .withHeader(CommOpen.toTypeString)
+ .withContentString(
+ CommOpen(TestCommId, TestTargetName, v5.MsgData.Empty)
+ )
+ .build
+ commOpenHandler ! msg
+
+ // Verify that the message sent by the handler has the desired property
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, _, parentHeader, _, _) =>
+ parentHeader == msg.header
+ }
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/ExecuteRequestHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/ExecuteRequestHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/ExecuteRequestHandlerSpec.scala
new file mode 100644
index 0000000..c22bc41
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/ExecuteRequestHandlerSpec.scala
@@ -0,0 +1,282 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import java.io.OutputStream
+import java.util.concurrent.atomic.AtomicInteger
+
+import akka.actor._
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import com.ibm.spark.kernel.api.{FactoryMethods, FactoryMethodsLike, Kernel}
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.kernel.protocol.v5.content._
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import com.ibm.spark.kernel.protocol.v5Test._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{BeforeAndAfter, FunSpecLike, Matchers}
+import play.api.libs.json.Json
+
+import org.mockito.Mockito._
+import org.mockito.Matchers._
+import scala.concurrent.duration._
+import scala.concurrent.ExecutionContext.Implicits.global
+import scala.concurrent._
+
+class ExecuteRequestHandlerSpec extends TestKit(
+ ActorSystem("ExecuteRequestHandlerSpec")
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+ with BeforeAndAfter {
+
+ private var mockActorLoader: ActorLoader = _
+ private var mockFactoryMethods: FactoryMethods = _
+ private var mockKernel: Kernel = _
+ private var mockOutputStream: OutputStream = _
+ private var handlerActor: ActorRef = _
+ private var kernelMessageRelayProbe: TestProbe = _
+ private var executeRequestRelayProbe: TestProbe = _
+ private var statusDispatchProbe: TestProbe = _
+
+ before {
+ mockActorLoader = mock[ActorLoader]
+ mockFactoryMethods = mock[FactoryMethods]
+ mockKernel = mock[Kernel]
+ mockOutputStream = mock[OutputStream]
+ doReturn(mockFactoryMethods).when(mockKernel)
+ .factory(any[KernelMessage], any[KMBuilder])
+
+ doReturn(mockOutputStream).when(mockFactoryMethods)
+ .newKernelOutputStream(anyString(), anyBoolean())
+
+ // Add our handler and mock interpreter to the actor system
+ handlerActor = system.actorOf(Props(
+ classOf[ExecuteRequestHandler],
+ mockActorLoader,
+ mockKernel
+ ))
+
+ kernelMessageRelayProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.KernelMessageRelay))
+ .thenReturn(system.actorSelection(kernelMessageRelayProbe.ref.path.toString))
+
+ executeRequestRelayProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.ExecuteRequestRelay))
+ .thenReturn(system.actorSelection(executeRequestRelayProbe.ref.path.toString))
+
+ statusDispatchProbe = new TestProbe(system)
+ when(mockActorLoader.load(SystemActorType.StatusDispatch))
+ .thenReturn(system.actorSelection(statusDispatchProbe.ref.path.toString))
+ }
+
+ /**
+ * This method simulates the interpreter passing back an
+ * execute result and reply.
+ */
+ def replyToHandlerWithOkAndResult() = {
+ // This stubs the behaviour of the interpreter executing code
+ val expectedClass = classOf[(ExecuteRequest, KernelMessage, OutputStream)]
+ executeRequestRelayProbe.expectMsgClass(expectedClass)
+ executeRequestRelayProbe.reply((
+ ExecuteReplyOk(1, Some(Payloads()), Some(UserExpressions())),
+ ExecuteResult(1, Data("text/plain" -> "resulty result"), Metadata())
+ ))
+ }
+
+ def replyToHandlerWithOk() = {
+ // This stubs the behaviour of the interpreter executing code
+ val expectedClass = classOf[(ExecuteRequest, KernelMessage, OutputStream)]
+ executeRequestRelayProbe.expectMsgClass(expectedClass)
+ executeRequestRelayProbe.reply((
+ ExecuteReplyOk(1, Some(Payloads()), Some(UserExpressions())),
+ ExecuteResult(1, Data("text/plain" -> ""), Metadata())
+ ))
+ }
+
+ /**
+ * This method simulates the interpreter passing back an
+ * execute result and reply
+ */
+ def replyToHandlerWithErrorAndResult() = {
+ // This stubs the behaviour of the interpreter executing code
+ val expectedClass = classOf[(ExecuteRequest, KernelMessage, OutputStream)]
+ executeRequestRelayProbe.expectMsgClass(expectedClass)
+ executeRequestRelayProbe.reply((
+ ExecuteReplyError(1, Some(""), Some(""), Some(Nil)),
+ ExecuteResult(1, Data("text/plain" -> "resulty result"), Metadata())
+ ))
+ }
+
+ describe("ExecuteRequestHandler( ActorLoader )") {
+ describe("#receive( KernelMessage ) when interpreter replies") {
+
+ it("should send an execute result message if the result is not empty") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ replyToHandlerWithOkAndResult()
+ kernelMessageRelayProbe.fishForMessage(100.milliseconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ header.msg_type == ExecuteResult.toTypeString
+ }
+ }
+
+ it("should not send an execute result message if there is no result") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ replyToHandlerWithOk()
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ header.msg_type != ExecuteResult.toTypeString
+ }
+
+ }
+
+ it("should send an execute reply message") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ replyToHandlerWithOkAndResult()
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ header.msg_type == ExecuteResult.toTypeString
+ }
+ }
+
+ it("should send a status idle message after the reply and result") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ replyToHandlerWithOkAndResult()
+
+ val msgCount = new AtomicInteger(0)
+ var statusMsgNum = -1
+ var statusReceived = false
+
+ val f1 = future {
+ kernelMessageRelayProbe.fishForMessage(4.seconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ if (header.msg_type == ExecuteResult.toTypeString &&
+ !statusReceived)
+ msgCount.incrementAndGet()
+ else if (header.msg_type == ExecuteReply.toTypeString &&
+ !statusReceived)
+ msgCount.incrementAndGet()
+ statusReceived || (msgCount.get() >= 2)
+ }
+ }
+
+ val f2 = future {
+ statusDispatchProbe.fishForMessage(4.seconds) {
+ case (status, header) =>
+ if (status == KernelStatusIdle.toString)
+ statusReceived = true
+ statusMsgNum = msgCount.get()
+ statusReceived || (msgCount.get() >= 2)
+ }
+ }
+ val fs = (f1 zip f2)
+ Await.ready(fs, 5.seconds)
+
+ statusMsgNum should equal(2)
+ }
+
+ it("should send an execute input message") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, header, _, _, _) =>
+ header.msg_type == ExecuteInput.toTypeString
+ }
+ }
+
+ it("should send a message with ids equal to the incoming " +
+ "KernelMessage's ids") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(ids, _, _, _, _, _) =>
+ ids == MockExecuteRequestKernelMessage.ids
+ }
+ }
+
+ it("should send a message with parent header equal to the incoming " +
+ "KernelMessage's header") {
+ handlerActor ! MockExecuteRequestKernelMessage
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ case KernelMessage(_, _, _, parentHeader, _, _) =>
+ parentHeader == MockExecuteRequestKernelMessage.header
+ }
+ }
+
+ // TODO: Investigate if this is still relevant at all
+// it("should send a status busy and idle message") {
+// handlerActor ! MockExecuteRequestKernelMessage
+// replyToHandlerWithOkAndResult()
+// var busy = false
+// var idle = false
+//
+// statusDispatchProbe.receiveWhile(100.milliseconds) {
+// case Tuple2(status: KernelStatusType, header: Header)=>
+// if(status == KernelStatusType.Busy)
+// busy = true
+// if(status == KernelStatusType.Idle)
+// idle = true
+// }
+//
+// idle should be (true)
+// busy should be (true)
+// }
+ }
+ }
+
+ // Testing error timeout for interpreter future
+ describe("ExecuteRequestHandler( ActorLoader )") {
+ describe("#receive( KernelMessage with bad JSON content )"){
+ it("should respond with an execute_reply with status error") {
+ handlerActor ! MockKernelMessageWithBadExecuteRequest
+
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ // Only mark as successful if this specific message was received
+ case KernelMessage(_, _, header, _, _, contentString)
+ if header.msg_type == ExecuteReply.toTypeString =>
+ val reply = Json.parse(contentString).as[ExecuteReply]
+ reply.status == "error"
+ case _ => false
+ }
+ }
+
+ it("should send error message to relay") {
+ handlerActor ! MockKernelMessageWithBadExecuteRequest
+
+ kernelMessageRelayProbe.fishForMessage(200.milliseconds) {
+ // Only mark as successful if this specific message was received
+ case KernelMessage(_, _, header, _, _, _)
+ if header.msg_type == ErrorContent.toTypeString => true
+ case _ => false
+ }
+ }
+
+ // TODO: Investigate if this is still relevant at all
+// it("should send a status idle message") {
+// handlerActor ! MockKernelMessageWithBadExecuteRequest
+// var busy = false
+// var idle = false
+//
+// statusDispatchProbe.receiveWhile(100.milliseconds) {
+// case Tuple2(status: KernelStatusType, header: Header)=>
+// if(status == KernelStatusType.Busy)
+// busy = true
+// if(status == KernelStatusType.Idle)
+// idle = true
+// }
+//
+// idle should be (true)
+// busy should be (false)
+// }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/GenericSocketMessageHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/GenericSocketMessageHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/GenericSocketMessageHandlerSpec.scala
new file mode 100644
index 0000000..54ebdc8
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/GenericSocketMessageHandlerSpec.scala
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import akka.actor.{ActorSystem, Props, ActorRef, ActorSelection}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import com.ibm.spark.kernel.protocol.v5Test._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, FunSpecLike, FunSpec}
+
+class GenericSocketMessageHandlerSpec extends TestKit(ActorSystem("GenericSocketMessageHandlerSystem"))
+with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+ describe("GenericSocketMessageHandler( ActorLoader, SocketType )") {
+ // Create a mock ActorLoader for the Relay we are going to test
+ val actorLoader: ActorLoader = mock[ActorLoader]
+
+ // Create a probe for the ActorSelection that the ActorLoader will return
+ val selectionProbe: TestProbe = TestProbe()
+ val selection: ActorSelection = system.actorSelection(selectionProbe.ref.path.toString)
+ when(actorLoader.load(SocketType.Control)).thenReturn(selection)
+
+ // The Relay we are going to be testing against
+ val genericHandler: ActorRef = system.actorOf(
+ Props(classOf[GenericSocketMessageHandler], actorLoader, SocketType.Control)
+ )
+
+ describe("#receive( KernelMessage )") {
+ genericHandler ! MockKernelMessage
+
+ it("should send the message to the selected actor"){
+ selectionProbe.expectMsg(MockKernelMessage)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/InputRequestReplyHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/InputRequestReplyHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/InputRequestReplyHandlerSpec.scala
new file mode 100644
index 0000000..57114bb
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/InputRequestReplyHandlerSpec.scala
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2015 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import java.util.UUID
+import java.util.concurrent.ConcurrentHashMap
+
+import akka.actor.{Props, ActorRef, ActorSystem}
+import akka.testkit.{TestProbe, ImplicitSender, TestKit}
+import com.ibm.spark.kernel.protocol.v5.content.InputReply
+import com.ibm.spark.kernel.protocol.v5.{HeaderBuilder, MessageType, KMBuilder, SystemActorType}
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import org.scalatest.concurrent.Eventually
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.time.{Milliseconds, Span}
+import org.scalatest.{BeforeAndAfter, FunSpecLike, Matchers}
+import scala.concurrent.duration._
+
+import org.mockito.Mockito._
+
+import collection.JavaConverters._
+
+class InputRequestReplyHandlerSpec
+ extends TestKit(ActorSystem("InputRequestReplyHandlerSystem"))
+ with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+ with BeforeAndAfter with Eventually
+{
+ implicit override val patienceConfig = PatienceConfig(
+ timeout = scaled(Span(200, Milliseconds)),
+ interval = scaled(Span(5, Milliseconds))
+ )
+
+ private var fakeSender: TestProbe = _
+ private var kernelMessageRelayProbe: TestProbe = _
+ private var mockActorLoader: ActorLoader = _
+ private var responseMap: collection.mutable.Map[String, ActorRef] = _
+
+ private var inputRequestReplyHandler: ActorRef = _
+
+ before {
+ fakeSender = TestProbe()
+
+ kernelMessageRelayProbe = TestProbe()
+ mockActorLoader = mock[ActorLoader]
+ doReturn(system.actorSelection(kernelMessageRelayProbe.ref.path.toString))
+ .when(mockActorLoader).load(SystemActorType.KernelMessageRelay)
+
+ responseMap = new ConcurrentHashMap[String, ActorRef]().asScala
+
+ inputRequestReplyHandler = system.actorOf(Props(
+ classOf[InputRequestReplyHandler], mockActorLoader, responseMap
+ ))
+ }
+
+ describe("InputRequestReplyHandler") {
+ describe("#receive") {
+ it("should store the sender under the session if input_request") {
+ val session = UUID.randomUUID().toString
+ val inputRequestMessage = KMBuilder()
+ .withParentHeader(HeaderBuilder.empty.copy(session = session))
+ .withHeader(MessageType.Outgoing.InputRequest)
+ .build
+
+ fakeSender.send(inputRequestReplyHandler, inputRequestMessage)
+
+ eventually {
+ responseMap(session) should be (fakeSender.ref)
+ }
+ }
+
+ it("should forward message to relay if input_request") {
+ val inputRequestMessage = KMBuilder()
+ .withHeader(MessageType.Outgoing.InputRequest)
+ .build
+
+ fakeSender.send(inputRequestReplyHandler, inputRequestMessage)
+
+ kernelMessageRelayProbe.expectMsg(inputRequestMessage)
+ }
+
+ it("should send the received message value to the stored sender with " +
+ "the same session if input_reply") {
+ val expected = "some value"
+ val session = UUID.randomUUID().toString
+
+ // Build the message to "get back from the world"
+ val inputReplyMessage = KMBuilder()
+ .withHeader(HeaderBuilder.empty.copy(
+ msg_type = MessageType.Incoming.InputReply.toString,
+ session = session
+ ))
+ .withContentString(InputReply(expected))
+ .build
+
+ // Add our fake sender actor to the receiving end of the message
+ responseMap(session) = fakeSender.ref
+
+ fakeSender.send(inputRequestReplyHandler, inputReplyMessage)
+
+ // Sender should receive a response
+ fakeSender.expectMsg(expected)
+ }
+
+ it("should do nothing if the session is not found for input_reply") {
+ val expected = "some value"
+ val session = UUID.randomUUID().toString
+
+ // Build the message to "get back from the world"
+ val inputReplyMessage = KMBuilder()
+ .withHeader(HeaderBuilder.empty.copy(
+ msg_type = MessageType.Incoming.InputReply.toString,
+ session = session
+ ))
+ .withContentString(InputReply(expected))
+ .build
+
+ fakeSender.send(inputRequestReplyHandler, inputReplyMessage)
+
+ // Sender should not receive a response
+ fakeSender.expectNoMsg(300.milliseconds)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/KernelInfoRequestHandlerSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/KernelInfoRequestHandlerSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/KernelInfoRequestHandlerSpec.scala
new file mode 100644
index 0000000..af44443
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/handler/KernelInfoRequestHandlerSpec.scala
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.handler
+
+import akka.actor.{ActorRef, ActorSelection, ActorSystem, Props}
+import akka.testkit.{TestProbe, ImplicitSender, TestKit}
+import com.ibm.spark.kernel.protocol.v5.content.KernelInfoReply
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import com.ibm.spark.kernel.protocol.v5.{SystemActorType, Header, KernelMessage}
+import org.mockito.AdditionalMatchers.{not => mockNot}
+import org.mockito.Matchers.{eq => mockEq}
+import com.typesafe.config.ConfigFactory
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpecLike, Matchers}
+import play.api.libs.json.Json
+
+import scala.concurrent.duration._
+
+object KernelInfoRequestHandlerSpec {
+ val config = """
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class KernelInfoRequestHandlerSpec extends TestKit(
+ ActorSystem("KernelInfoRequestHandlerSpec",
+ ConfigFactory.parseString(KernelInfoRequestHandlerSpec.config))
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+ val actorLoader: ActorLoader = mock[ActorLoader]
+ val actor = system.actorOf(Props(classOf[KernelInfoRequestHandler], actorLoader))
+
+ val relayProbe : TestProbe = TestProbe()
+ val relaySelection : ActorSelection =
+ system.actorSelection(relayProbe.ref.path)
+ when(actorLoader.load(SystemActorType.KernelMessageRelay))
+ .thenReturn(relaySelection)
+ when(actorLoader.load(mockNot(mockEq(SystemActorType.KernelMessageRelay))))
+ .thenReturn(system.actorSelection(""))
+
+ val header = Header("","","","","")
+ val kernelMessage = new KernelMessage(
+ Seq[String](), "test message", header, header, Map[String, String](), "{}"
+ )
+
+ describe("Kernel Info Request Handler") {
+ it("should return a KernelMessage containing kernel info response") {
+ actor ! kernelMessage
+ val reply = relayProbe.receiveOne(1.seconds).asInstanceOf[KernelMessage]
+ val kernelInfo = Json.parse(reply.contentString).as[KernelInfoReply]
+ kernelInfo.implementation should be ("spark")
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/interpreter/tasks/ExecuteRequestTaskActorSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/interpreter/tasks/ExecuteRequestTaskActorSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/interpreter/tasks/ExecuteRequestTaskActorSpec.scala
new file mode 100644
index 0000000..be982cb
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/interpreter/tasks/ExecuteRequestTaskActorSpec.scala
@@ -0,0 +1,181 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.interpreter.tasks
+
+import java.io.OutputStream
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit}
+import com.ibm.spark.interpreter._
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.kernel.protocol.v5.content._
+import com.typesafe.config.ConfigFactory
+import org.mockito.Mockito._
+import org.mockito.Matchers.{eq => mockEq, anyString, anyBoolean}
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, FunSpecLike}
+
+import scala.concurrent.duration._
+
+object ExecuteRequestTaskActorSpec {
+ val config = """
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class ExecuteRequestTaskActorSpec extends TestKit(
+ ActorSystem(
+ "ExecuteRequestTaskActorSpec",
+ ConfigFactory.parseString(ExecuteRequestTaskActorSpec.config)
+ )
+) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar
+{
+ describe("ExecuteRequestTaskActor") {
+ describe("#receive") {
+ it("should return an ExecuteReplyOk if the interpreter returns success") {
+ val mockInterpreter = mock[Interpreter]
+ doReturn((Results.Success, Left(new ExecuteOutput))).when(mockInterpreter)
+ .interpret(anyString(), anyBoolean())
+
+ val executeRequestTask =
+ system.actorOf(Props(
+ classOf[ExecuteRequestTaskActor],
+ mockInterpreter
+ ))
+
+ val executeRequest = (ExecuteRequest(
+ "val x = 3", false, false,
+ UserExpressions(), false
+ ), mock[KernelMessage], mock[OutputStream])
+
+ executeRequestTask ! executeRequest
+
+ val result =
+ receiveOne(5.seconds)
+ .asInstanceOf[Either[ExecuteOutput, ExecuteError]]
+
+ result.isLeft should be (true)
+ result.left.get shouldBe an [ExecuteOutput]
+ }
+
+ it("should return an ExecuteReplyAbort if the interpreter returns aborted") {
+ val mockInterpreter = mock[Interpreter]
+ doReturn((Results.Aborted, Right(mock[ExecuteAborted]))).when(mockInterpreter)
+ .interpret(anyString(), anyBoolean())
+
+ val executeRequestTask =
+ system.actorOf(Props(
+ classOf[ExecuteRequestTaskActor],
+ mockInterpreter
+ ))
+
+ val executeRequest = (ExecuteRequest(
+ "val x = 3", false, false,
+ UserExpressions(), false
+ ), mock[KernelMessage], mock[OutputStream])
+
+ executeRequestTask ! executeRequest
+
+ val result =
+ receiveOne(5.seconds)
+ .asInstanceOf[Either[ExecuteOutput, ExecuteFailure]]
+
+ result.isRight should be (true)
+ result.right.get shouldBe an [ExecuteAborted]
+ }
+
+ it("should return an ExecuteReplyError if the interpreter returns error") {
+ val mockInterpreter = mock[Interpreter]
+ doReturn((Results.Error, Right(mock[ExecuteError]))).when(mockInterpreter)
+ .interpret(anyString(), anyBoolean())
+
+ val executeRequestTask =
+ system.actorOf(Props(
+ classOf[ExecuteRequestTaskActor],
+ mockInterpreter
+ ))
+
+ val executeRequest = (ExecuteRequest(
+ "val x = 3", false, false,
+ UserExpressions(), false
+ ), mock[KernelMessage], mock[OutputStream])
+
+ executeRequestTask ! executeRequest
+
+ val result =
+ receiveOne(5.seconds)
+ .asInstanceOf[Either[ExecuteOutput, ExecuteError]]
+
+ result.isRight should be (true)
+ result.right.get shouldBe an [ExecuteError]
+ }
+
+ it("should return ExecuteReplyError if interpreter returns incomplete") {
+ val mockInterpreter = mock[Interpreter]
+ doReturn((Results.Incomplete, Right(""))).when(mockInterpreter)
+ .interpret(anyString(), anyBoolean())
+
+ val executeRequestTask =
+ system.actorOf(Props(
+ classOf[ExecuteRequestTaskActor],
+ mockInterpreter
+ ))
+
+ val executeRequest = (ExecuteRequest(
+ "(1 + 2", false, false,
+ UserExpressions(), false
+ ), mock[KernelMessage], mock[OutputStream])
+
+ executeRequestTask ! executeRequest
+
+ val result =
+ receiveOne(5.seconds)
+ .asInstanceOf[Either[ExecuteOutput, ExecuteError]]
+
+ result.isLeft should be (false)
+ result.right.get shouldBe an [ExecuteError]
+ }
+
+ it("should return an ExecuteReplyOk when receiving empty code.") {
+ val mockInterpreter = mock[Interpreter]
+ doReturn((Results.Incomplete, Right(""))).when(mockInterpreter)
+ .interpret(anyString(), anyBoolean())
+
+ val executeRequestTask =
+ system.actorOf(Props(
+ classOf[ExecuteRequestTaskActor],
+ mockInterpreter
+ ))
+
+ val executeRequest = (ExecuteRequest(
+ " ", false, false,
+ UserExpressions(), false
+ ), mock[KernelMessage], mock[OutputStream])
+
+ executeRequestTask ! executeRequest
+
+ val result =
+ receiveOne(5.seconds)
+ .asInstanceOf[Either[ExecuteOutput, ExecuteError]]
+
+ result.isLeft should be (true)
+ result.isRight should be (false)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/ActorLoaderSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/ActorLoaderSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/ActorLoaderSpec.scala
new file mode 100644
index 0000000..8bb5f40
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/ActorLoaderSpec.scala
@@ -0,0 +1,73 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import com.ibm.spark.kernel.protocol.v5.{MessageType, SocketType}
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpecLike, Matchers}
+import test.utils.TestProbeProxyActor
+
+import scala.concurrent.duration._
+
+class ActorLoaderSpec extends TestKit(ActorSystem("ActorLoaderSpecSystem"))
+with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+ describe("ActorLoader"){
+ describe("#load( MessageType )"){
+ it("should load an ActorSelection that has been loaded into the system"){
+ val testProbe: TestProbe = TestProbe()
+ system.actorOf(Props(classOf[TestProbeProxyActor], testProbe),
+ MessageType.Outgoing.ClearOutput.toString)
+ val actorLoader: ActorLoader = SimpleActorLoader(system)
+ actorLoader.load(MessageType.Outgoing.ClearOutput) ! "<Test Message>"
+ testProbe.expectMsg("<Test Message>")
+ }
+
+ it("should expect no message when there is no actor"){
+ val testProbe: TestProbe = TestProbe()
+ val actorLoader: ActorLoader = SimpleActorLoader(system)
+ actorLoader.load(MessageType.Outgoing.CompleteReply) ! "<Test Message>"
+ testProbe.expectNoMsg(25.millis)
+ // This is to test to see if there the messages go to the actor inbox or the dead mail inbox
+ system.actorOf(Props(classOf[TestProbeProxyActor], testProbe),
+ MessageType.Outgoing.CompleteReply.toString)
+ testProbe.expectNoMsg(25.millis)
+ }
+ }
+ describe("#load( SocketType )"){
+ it("should load an ActorSelection that has been loaded into the system"){
+ val testProbe: TestProbe = TestProbe()
+ system.actorOf(Props(classOf[TestProbeProxyActor], testProbe), SocketType.Shell.toString)
+ val actorLoader: ActorLoader = SimpleActorLoader(system)
+ actorLoader.load(SocketType.Shell) ! "<Test Message>"
+ testProbe.expectMsg("<Test Message>")
+ }
+
+ it("should expect no message when there is no actor"){
+ val testProbe: TestProbe = TestProbe()
+ val actorLoader: ActorLoader = SimpleActorLoader(system)
+ actorLoader.load(SocketType.IOPub) ! "<Test Message>"
+ testProbe.expectNoMsg(25.millis)
+ // This is to test to see if there the messages go to the actor inbox or the dead mail inbox
+ system.actorOf(Props(classOf[TestProbeProxyActor], testProbe), SocketType.IOPub.toString)
+ testProbe.expectNoMsg(25.millis)
+ }
+
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/SimpleActorLoaderSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/SimpleActorLoaderSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/SimpleActorLoaderSpec.scala
new file mode 100644
index 0000000..65f0990
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/SimpleActorLoaderSpec.scala
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel
+
+import akka.actor.{ActorSelection, ActorSystem, Props}
+import akka.testkit.{TestKit, TestProbe}
+import com.ibm.spark.kernel.protocol.v5.MessageType
+import org.scalatest.{FunSpecLike, Matchers}
+import test.utils.TestProbeProxyActor
+
+class SimpleActorLoaderSpec extends TestKit(ActorSystem("SimpleActorLoaderSpecSystem"))
+ with FunSpecLike with Matchers
+{
+ describe("SimpleActorLoader") {
+ //val system = ActorSystem("SimpleActorLoaderSystem")
+ val testMessage: String = "Hello Message"
+
+ describe("#load( MessageType )") {
+ it("should load a MessageType Actor"){
+ // Create a new test probe to verify our selection works
+ val messageTypeProbe: TestProbe = new TestProbe(system)
+
+ // Add an actor to the system to send a message to
+ system.actorOf(
+ Props(classOf[TestProbeProxyActor], messageTypeProbe),
+ name = MessageType.Outgoing.ExecuteInput.toString
+ )
+
+ // Create the ActorLoader with our test system
+ val actorLoader: SimpleActorLoader = SimpleActorLoader(system)
+
+ // Get the actor and send it a message
+ val loadedMessageActor: ActorSelection =
+ actorLoader.load(MessageType.Outgoing.ExecuteInput)
+
+ loadedMessageActor ! testMessage
+
+ // Assert the probe received the message
+ messageTypeProbe.expectMsg(testMessage)
+ }
+ }
+
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/UtilitiesSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/UtilitiesSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/UtilitiesSpec.scala
new file mode 100644
index 0000000..67c6eeb
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/UtilitiesSpec.scala
@@ -0,0 +1,112 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel
+
+import akka.util.ByteString
+import com.ibm.spark.communication.ZMQMessage
+import com.ibm.spark.kernel.protocol.v5._
+import org.scalatest.{FunSpec, Matchers}
+
+/**
+ * Refactored from old KernelMessageSpec.
+ */
+class UtilitiesSpec extends FunSpec with Matchers {
+ val header: Header = Header(
+ "<UUID>", "<STRING>", "<UUID>", "<STRING>", "<FLOAT>"
+ )
+ val parentHeader : ParentHeader = ParentHeader(
+ "<PARENT-UUID>", "<PARENT-STRING>", "<PARENT-UUID>", "<PARENT-STRING>", "<PARENT-FLOAT>"
+ )
+ val kernelMessage = KernelMessage(
+ Seq("<STRING-1>","<STRING-2>"),
+ "<SIGNATURE>", header, parentHeader, Map(), "<STRING>"
+ )
+
+ val zmqMessage = ZMQMessage(
+ ByteString("<STRING-1>".replaceAll("""\s""", "").getBytes),
+ ByteString("<STRING-2>".replaceAll("""\s""", "").getBytes),
+ ByteString("<IDS|MSG>".replaceAll("""\s""", "").getBytes),
+ ByteString("<SIGNATURE>".replaceAll("""\s""", "").getBytes),
+ ByteString(
+ """
+ {
+ "msg_id": "<UUID>",
+ "username": "<STRING>",
+ "session": "<UUID>",
+ "msg_type": "<STRING>",
+ "version": "<FLOAT>"
+ }
+ """.stripMargin.replaceAll("""\s""", "").getBytes),
+ ByteString(
+ """
+ {
+ "msg_id": "<PARENT-UUID>",
+ "username": "<PARENT-STRING>",
+ "session": "<PARENT-UUID>",
+ "msg_type": "<PARENT-STRING>",
+ "version": "<PARENT-FLOAT>"
+ }
+ """.stripMargin.replaceAll("""\s""", "").getBytes),
+ ByteString("{}".replaceAll("""\s""", "").getBytes),
+ ByteString("<STRING>".replaceAll("""\s""", "").getBytes)
+ )
+
+ describe("Utilities") {
+ describe("implicit #KernelMessageToZMQMessage") {
+ it("should correctly convert a kernel message to a ZMQMessage") {
+ Utilities.KernelMessageToZMQMessage(kernelMessage) should be (zmqMessage)
+ }
+ }
+
+ describe("implicit #ZMQMessageToKernelMessage") {
+ it("should correctly convert a ZMQMessage to a kernel message") {
+ Utilities.ZMQMessageToKernelMessage(zmqMessage) should be (kernelMessage)
+ }
+ }
+
+ describe("implicit conversions should be inverses of each other") {
+ it("should convert back to the original message, ZMQ -> Kernel -> ZMQ") {
+ Utilities.KernelMessageToZMQMessage(
+ Utilities.ZMQMessageToKernelMessage(zmqMessage)
+ ) should be (zmqMessage)
+ }
+ it("should convert back to the original message, Kernel -> ZMQ -> Kernel") {
+ Utilities.ZMQMessageToKernelMessage(
+ Utilities.KernelMessageToZMQMessage(kernelMessage)
+ ) should be (kernelMessage)
+ }
+ }
+
+ describe("implicit #StringToByteString") {
+ it("should correctly convert a string to a ByteString") {
+ val someString = "some content"
+ val expected = ByteString(someString)
+
+ Utilities.StringToByteString(someString) should be (expected)
+ }
+ }
+
+ describe("implicit #ByteStringToString") {
+ it("should correctly convert a ByteString to a string") {
+ val expected = "some content"
+ val byteString = ByteString(expected)
+
+ Utilities.ByteStringToString(byteString) should be (expected)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/HeartbeatSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/HeartbeatSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/HeartbeatSpec.scala
new file mode 100644
index 0000000..388f466
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/HeartbeatSpec.scala
@@ -0,0 +1,55 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import akka.actor.{ActorRef, ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import akka.util.ByteString
+import com.ibm.spark.communication.ZMQMessage
+import com.typesafe.config.ConfigFactory
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpecLike, Matchers}
+
+object HeartbeatSpec {
+ val config = """
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class HeartbeatSpec extends TestKit(ActorSystem("HeartbeatActorSpec", ConfigFactory.parseString(HeartbeatSpec.config)))
+with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+ val SomeMessage: String = "some message"
+ val SomeZMQMessage: ZMQMessage = ZMQMessage(ByteString(SomeMessage.getBytes))
+
+ describe("HeartbeatActor") {
+ val socketFactory = mock[SocketFactory]
+ val probe : TestProbe = TestProbe()
+ when(socketFactory.Heartbeat(any(classOf[ActorSystem]), any(classOf[ActorRef]))).thenReturn(probe.ref)
+
+ val heartbeat = system.actorOf(Props(classOf[Heartbeat], socketFactory))
+
+ describe("send heartbeat") {
+ it("should receive and send same ZMQMessage") {
+ heartbeat ! SomeZMQMessage
+ probe.expectMsg(SomeZMQMessage)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/IOPubSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/IOPubSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/IOPubSpec.scala
new file mode 100644
index 0000000..6e6fdb3
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/IOPubSpec.scala
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import akka.actor.{ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import com.ibm.spark.communication.ZMQMessage
+import com.ibm.spark.kernel.protocol.v5.kernel.Utilities
+import com.ibm.spark.kernel.protocol.v5Test._
+import Utilities._
+import com.typesafe.config.ConfigFactory
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpecLike, Matchers}
+
+object IOPubSpec {
+ val config ="""
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class IOPubSpec extends TestKit(ActorSystem("IOPubActorSpec", ConfigFactory.parseString(IOPubSpec.config)))
+with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+
+ describe("IOPubActor") {
+ val socketFactory = mock[SocketFactory]
+ val probe : TestProbe = TestProbe()
+ when(socketFactory.IOPub(any(classOf[ActorSystem]))).thenReturn(probe.ref)
+
+ val socket = system.actorOf(Props(classOf[IOPub], socketFactory))
+
+ // TODO test that the response type changed
+ describe("#receive") {
+ it("should reply with a ZMQMessage") {
+ // Use the implicit to convert the KernelMessage to ZMQMessage
+ val MockZMQMessage : ZMQMessage = MockKernelMessage
+
+ socket ! MockKernelMessage
+ probe.expectMsg(MockZMQMessage)
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/ShellSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/ShellSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/ShellSpec.scala
new file mode 100644
index 0000000..d28a5ae
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/ShellSpec.scala
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import java.nio.charset.Charset
+
+import akka.actor.{ActorSelection, ActorRef, ActorSystem, Props}
+import akka.testkit.{ImplicitSender, TestKit, TestProbe}
+import akka.util.ByteString
+import com.ibm.spark.communication.ZMQMessage
+import com.ibm.spark.kernel.protocol.v5._
+import com.ibm.spark.kernel.protocol.v5.kernel.{ActorLoader, Utilities}
+import com.ibm.spark.kernel.protocol.v5Test._
+import Utilities._
+import com.typesafe.config.ConfigFactory
+import org.mockito.Matchers._
+import org.mockito.Mockito._
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpecLike, Matchers}
+
+object ShellSpec {
+ val config ="""
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class ShellSpec extends TestKit(ActorSystem("ShellActorSpec", ConfigFactory.parseString(ShellSpec.config)))
+ with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+
+ describe("Shell") {
+ val socketFactory = mock[SocketFactory]
+ val actorLoader = mock[ActorLoader]
+ val socketProbe : TestProbe = TestProbe()
+ when(socketFactory.Shell(any(classOf[ActorSystem]), any(classOf[ActorRef]))).thenReturn(socketProbe.ref)
+
+ val relayProbe : TestProbe = TestProbe()
+ val relaySelection : ActorSelection = system.actorSelection(relayProbe.ref.path)
+ when(actorLoader.load(SystemActorType.KernelMessageRelay)).thenReturn(relaySelection)
+
+ val shell = system.actorOf(Props(classOf[Shell], socketFactory, actorLoader))
+
+ describe("#receive") {
+ it("( KernelMessage ) should reply with a ZMQMessage via the socket") {
+ // Use the implicit to convert the KernelMessage to ZMQMessage
+ val MockZMQMessage : ZMQMessage = MockKernelMessage
+
+ shell ! MockKernelMessage
+ socketProbe.expectMsg(MockZMQMessage)
+ }
+
+ it("( ZMQMessage ) should forward ZMQ Strings and KernelMessage to Relay") {
+ // Use the implicit to convert the KernelMessage to ZMQMessage
+ val MockZMQMessage : ZMQMessage = MockKernelMessage
+
+ shell ! MockZMQMessage
+
+ // Should get the last four (assuming no buffer) strings in UTF-8
+ val zmqStrings = MockZMQMessage.frames.map((byteString: ByteString) =>
+ new String(byteString.toArray, Charset.forName("UTF-8"))
+ ).takeRight(4)
+
+ val kernelMessage: KernelMessage = MockZMQMessage
+
+ relayProbe.expectMsg((zmqStrings, kernelMessage))
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConfigSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConfigSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConfigSpec.scala
new file mode 100644
index 0000000..b36f734
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConfigSpec.scala
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import com.typesafe.config.ConfigFactory
+import org.scalatest.{FunSpec, Matchers}
+import org.slf4j.LoggerFactory
+import play.api.data.validation.ValidationError
+import play.api.libs.json.{JsPath, JsValue, Json}
+
+class SocketConfigSpec extends FunSpec with Matchers {
+ val logger = LoggerFactory.getLogger("jt4")
+ //logger.error("WOOT!")
+
+ private val jsonString: String =
+ """
+ {
+ "stdin_port": 10000,
+ "control_port": 10001,
+ "hb_port": 10002,
+ "shell_port": 10003,
+ "iopub_port": 10004,
+ "ip": "1.2.3.4",
+ "transport": "tcp",
+ "signature_scheme": "hmac-sha256",
+ "key": ""
+ }
+ """.stripMargin
+
+ val socketConfigJson: JsValue = Json.parse(jsonString)
+
+ val socketConfigFromConfig = SocketConfig.fromConfig(ConfigFactory.parseString(jsonString))
+
+ val socketConfig = SocketConfig(
+ 10000, 10001, 10002, 10003, 10004, "1.2.3.4", "tcp", "hmac-sha256", ""
+ )
+
+ describe("SocketConfig") {
+ describe("implicit conversions") {
+ it("should implicitly convert from valid json to a SocketConfig instance") {
+ // This is the least safe way to convert as an error is thrown if it fails
+ socketConfigJson.as[SocketConfig] should be (socketConfig)
+ }
+
+ it("should also work with asOpt") {
+ // This is safer, but we lose the error information as it returns
+ // None if the conversion fails
+ val newCompleteRequest = socketConfigJson.asOpt[SocketConfig]
+
+ newCompleteRequest.get should be (socketConfig)
+ }
+
+ it("should also work with validate") {
+ // This is the safest as it collects all error information (not just first error) and reports it
+ val CompleteRequestResults = socketConfigJson.validate[SocketConfig]
+
+ CompleteRequestResults.fold(
+ (invalid: Seq[(JsPath, Seq[ValidationError])]) => println("Failed!"),
+ (valid: SocketConfig) => valid
+ ) should be (socketConfig)
+ }
+
+ it("should implicitly convert from a SocketConfig instance to valid json") {
+ Json.toJson(socketConfig) should be (socketConfigJson)
+ }
+ }
+ describe("#toConfig") {
+ it("should implicitly convert from valid json to a SocketConfig instance") {
+ // This is the least safe way to convert as an error is thrown if it fails
+ socketConfigFromConfig should be (socketConfig)
+ }
+
+ it("should convert json file to SocketConfig object") {
+ socketConfigFromConfig.stdin_port should be (10000)
+ }
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConnectionSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConnectionSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConnectionSpec.scala
new file mode 100644
index 0000000..f33ddc0
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketConnectionSpec.scala
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import org.scalatest.{FunSpec, Matchers}
+
+class SocketConnectionSpec extends FunSpec with Matchers {
+ describe("SocketConnection"){
+ describe("#toString"){
+ it("should properly format connection string"){
+ val connection: SocketConnection = SocketConnection("tcp", "127.0.0.1", 1234)
+ connection.toString should be ("tcp://127.0.0.1:1234")
+ }
+ }
+ }
+
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketFactorySpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketFactorySpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketFactorySpec.scala
new file mode 100644
index 0000000..abefdb3
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/SocketFactorySpec.scala
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2014 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import org.scalatest.{FunSpec, Matchers}
+
+class SocketFactorySpec extends FunSpec with Matchers {
+ describe("SocketFactory"){
+ describe("HeartbeatConnection"){
+ it("should be composed of transport ip and heartbeat port"){
+ val config: SocketConfig = SocketConfig(-1,-1,8000,-1, -1, "<STRING-IP>", "<STRING-TRANSPORT>","<STRING-SCHEME>","<STRING-KEY>")
+ val factory: SocketFactory = SocketFactory(config)
+ factory.HeartbeatConnection.toString should be ("<STRING-TRANSPORT>://<STRING-IP>:8000")
+ }
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/StdinSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/StdinSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/StdinSpec.scala
new file mode 100644
index 0000000..2103904
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/kernel/socket/StdinSpec.scala
@@ -0,0 +1,84 @@
+/*
+ * Copyright 2015 IBM Corp.
+ *
+ * Licensed 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.ibm.spark.kernel.protocol.v5.kernel.socket
+
+import java.nio.charset.Charset
+
+import akka.actor.{Props, ActorSelection, ActorRef, ActorSystem}
+import akka.testkit.{TestProbe, ImplicitSender, TestKit}
+import akka.util.ByteString
+import com.ibm.spark.communication.ZMQMessage
+import com.ibm.spark.kernel.protocol.v5.kernel.Utilities._
+import com.ibm.spark.kernel.protocol.v5Test._
+import com.ibm.spark.kernel.protocol.v5.{KernelMessage, SystemActorType}
+import com.ibm.spark.kernel.protocol.v5.kernel.ActorLoader
+import com.typesafe.config.ConfigFactory
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{Matchers, FunSpecLike}
+import org.mockito.Mockito._
+import org.mockito.Matchers._
+
+object StdinSpec {
+ val config ="""
+ akka {
+ loglevel = "WARNING"
+ }"""
+}
+
+class StdinSpec extends TestKit(ActorSystem(
+ "StdinActorSpec", ConfigFactory.parseString(StdinSpec.config)
+)) with ImplicitSender with FunSpecLike with Matchers with MockitoSugar {
+ describe("Stdin") {
+ val socketFactory = mock[SocketFactory]
+ val actorLoader = mock[ActorLoader]
+ val socketProbe : TestProbe = TestProbe()
+ when(socketFactory.Stdin(any(classOf[ActorSystem]), any(classOf[ActorRef]))).thenReturn(socketProbe.ref)
+
+ val relayProbe : TestProbe = TestProbe()
+ val relaySelection : ActorSelection = system.actorSelection(relayProbe.ref.path)
+ when(actorLoader.load(SystemActorType.KernelMessageRelay)).thenReturn(relaySelection)
+
+ val stdin = system.actorOf(Props(classOf[Stdin], socketFactory, actorLoader))
+
+ describe("#receive") {
+ it("( KernelMessage ) should reply with a ZMQMessage via the socket") {
+ // Use the implicit to convert the KernelMessage to ZMQMessage
+ val MockZMQMessage : ZMQMessage = MockKernelMessage
+
+ stdin ! MockKernelMessage
+ socketProbe.expectMsg(MockZMQMessage)
+ }
+
+ it("( ZMQMessage ) should forward ZMQ Strings and KernelMessage to Relay") {
+ // Use the implicit to convert the KernelMessage to ZMQMessage
+ val MockZMQMessage : ZMQMessage = MockKernelMessage
+
+ stdin ! MockZMQMessage
+
+ // Should get the last four (assuming no buffer) strings in UTF-8
+ val zmqStrings = MockZMQMessage.frames.map((byteString: ByteString) =>
+ new String(byteString.toArray, Charset.forName("UTF-8"))
+ ).takeRight(4)
+
+ val kernelMessage: KernelMessage = MockZMQMessage
+
+ relayProbe.expectMsg((zmqStrings, kernelMessage))
+ }
+ }
+ }
+}
+
http://git-wip-us.apache.org/repos/asf/incubator-toree/blob/68f7ddd6/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/magic/MagicParserSpec.scala
----------------------------------------------------------------------
diff --git a/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/magic/MagicParserSpec.scala b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/magic/MagicParserSpec.scala
new file mode 100644
index 0000000..ba3415f
--- /dev/null
+++ b/kernel/src/test/scala/org/apache/toree/kernel/protocol/v5/magic/MagicParserSpec.scala
@@ -0,0 +1,237 @@
+package com.ibm.spark.kernel.protocol.v5.magic
+
+import com.ibm.spark.magic.MagicLoader
+import org.scalatest.mock.MockitoSugar
+import org.scalatest.{FunSpec, Matchers}
+import org.mockito.Mockito._
+import org.mockito.Matchers._
+
+class MagicParserSpec extends FunSpec with Matchers with MockitoSugar {
+ describe("#parse") {
+ it("should call parseCell if the code is a cell magic invocation") {
+ val codeBlob =
+ """
+ |%%magic
+ |foo
+ |bean
+ """.stripMargin
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ parser.parse(codeBlob)
+ verify(parser).parseCell(codeBlob.trim)
+ }
+
+ it("should call parseLines if the code is not a cell magic") {
+ val codeBlob = """%magic foo bean"""
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ parser.parse(codeBlob)
+ verify(parser).parseLines(codeBlob.trim)
+ }
+ }
+
+ describe("#parseCell") {
+ it("should substitute the magic code for kernel code when magic is valid") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(true).when(magicLoader).hasCellMagic(anyString())
+
+ val magicName = "magic"
+ val args = "foo\nbean\nbar"
+ val codeBlob =
+ s"""%%$magicName
+ |$args
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseCell(codeBlob)
+
+ verify(parser).substitute(magicName, args)
+ result.isLeft should be(true)
+ }
+
+ it("should return an error if the magic invocation is invalid") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(false).when(magicLoader).hasCellMagic(anyString())
+
+ val magicName = "magic"
+ val args = "foo\nbean\nbar"
+ val codeBlob =
+ s"""%%$magicName
+ |$args
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseCell(codeBlob)
+
+ verify(parser, times(0)).substitute(anyString(), anyString())
+ result.isRight should be(true)
+ }
+
+ it("should return original code if code contains no magic invocations") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(false).when(magicLoader).hasCellMagic(anyString())
+
+ val codeBlob =
+ s"""val x = 3
+ |println(x + 2)
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseCell(codeBlob)
+
+ verify(parser, times(0)).substitute(anyString(), anyString())
+ result.isLeft should be(true)
+ result.left.get should be(codeBlob)
+ }
+ }
+
+ describe("#parseLines") {
+ it("should call substituteLine for each line of code " +
+ "when there are no invalid magic invocations") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(true).when(magicLoader).hasLineMagic(anyString())
+
+ val codeBlob =
+ s"""val x = 3
+ |%lineMagic
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseLines(codeBlob)
+
+ verify(parser, times(2)).substituteLine(anyString())
+ result.isLeft should be(true)
+ }
+
+ it("should return an error when there are invalid magic invocations") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(false).when(magicLoader).hasLineMagic(anyString())
+
+ val codeBlob =
+ s"""val x = 3
+ |%lineMagic
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseLines(codeBlob)
+
+ verify(parser, times(0)).substituteLine(anyString())
+ result.isRight should be(true)
+ }
+
+ it("should return original code when there are no magic invocations") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(false).when(magicLoader).hasLineMagic(anyString())
+
+ val codeBlob =
+ s"""val x = 3
+ |val y = x + 2
+ """.stripMargin
+ val parser = spy(new MagicParser(magicLoader))
+ val result = parser.parseLines(codeBlob.trim)
+
+ result.isLeft should be(true)
+ result.left.get should be(codeBlob.trim)
+ }
+ }
+
+ describe("#parseMagic") {
+ it("should extract the cell name and arguments from a valid invocation") {
+ val magicName = "foobar"
+ val magicArgs = "baz\nbean"
+ val codeBlob = s"""%%$magicName\n$magicArgs"""
+ val parser = new MagicParser(mock[MagicLoader])
+ parser.parseMagic(codeBlob) should be(Some((magicName, magicArgs)))
+ }
+
+ it("should extract the line name and arguments from a valid invocation") {
+ val magicName = "foobar"
+ val magicArgs = "baz\nbean"
+ val codeBlob = s"""%$magicName $magicArgs"""
+ val parser = new MagicParser(mock[MagicLoader])
+ parser.parseMagic(codeBlob) should be(Some((magicName, magicArgs)))
+ }
+
+ it("should return none if the invocation was not valid") {
+ val magicName = "foobar"
+ val magicArgs = "baz\nbean"
+ val codeBlob = s"""$magicName\n$magicArgs"""
+ val parser = new MagicParser(mock[MagicLoader])
+ parser.parseMagic(codeBlob) should be(None)
+ }
+ }
+
+ describe("#substituteLine") {
+ it("should call substitute when a codeLine is a valid magic invocation") {
+ val magicName = "magic"
+ val args = "-v foo bar"
+ val codeLine = s"""%$magicName $args"""
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ doReturn(true).when(parser).isValidLineMagic(anyString())
+ parser.substituteLine(codeLine)
+ verify(parser).substitute(magicName, args)
+ }
+
+ it("should return original line of code when it's not a valid +" +
+ "magic invocation") {
+ val codeLine = """val x = 3"""
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ doReturn(false).when(parser).isValidLineMagic(anyString())
+ parser.substituteLine(codeLine) should be(codeLine)
+ }
+ }
+
+ describe("#substitute") {
+ // pointless?
+ it("should replace a magic invocation with an equivalent kernel call") {
+ val magicName = "magic"
+ val args = "foo bean"
+ val parser = new MagicParser(mock[MagicLoader])
+
+ val equivalent =
+ s"""${parser.kernelObjectName}.$magicName(\"\"\"$args\"\"\")"""
+ parser.substitute(magicName, args) should be(equivalent)
+ }
+ }
+
+ describe("#parseOutInvalidMagics") {
+ it("it should return the names of invalid magics") {
+ val magicOne = "foo"
+ val magicTwo = "qux"
+ val codeBlob =
+ s"""
+ |%$magicOne bar baz
+ |%$magicTwo quo bean
+ """.stripMargin
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ doReturn(false).when(parser).isValidLineMagic(anyString())
+
+ parser.parseOutInvalidMagics(codeBlob) should be(List(magicOne, magicTwo))
+ }
+
+ it("it should nothing if all magic invocations are valid") {
+ val magicOne = "foo"
+ val magicTwo = "qux"
+ val codeBlob =
+ s"""
+ |%$magicOne bar baz
+ |%$magicTwo quo bean
+ """.stripMargin
+ val parser = spy(new MagicParser(mock[MagicLoader]))
+ doReturn(true).when(parser).isValidLineMagic(anyString())
+
+ parser.parseOutInvalidMagics(codeBlob) should be(Nil)
+ }
+ }
+
+ describe("#isValidLineMagic") {
+ it("should return true if the line magic invocation is valid") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(true).when(magicLoader).hasLineMagic(anyString())
+
+ val parser = new MagicParser(magicLoader)
+ parser.isValidLineMagic("%foobar baz") should be(true)
+ }
+
+ it("should return false if the line magic invocation is not valid") {
+ val magicLoader = mock[MagicLoader]
+ doReturn(false).when(magicLoader).hasLineMagic(anyString())
+
+ val parser = new MagicParser(magicLoader)
+ parser.isValidLineMagic("%foobar baz") should be(false)
+ }
+ }
+}