SlideShare ist ein Scribd-Unternehmen logo
1 von 19
Downloaden Sie, um offline zu lesen
testing spray.io
in 45 minutes
The Plan
● What spray is
● What we are testing
● How
Spray
“an open-source toolkit for building
REST/HTTP-based integration layers on top of
Scala and Akka”
Spray
“an open-source toolkit for building
REST/HTTP-based integration layers on top of
Scala and Akka”
Library to wrap services with REST API
REST API
● request routing
● (un)marshalling to / from domain objects
● authentication / authorization
● encoding / decoding (compression)
● serving static content
● caching
REST API
● request routing - headers, params and paths
● (un)marshalling to / from domain objects - req/resp entity
● authentication / authorization - directives
● encoding / decoding (compression) - Gzip, Deflate
● serving static content - the same way as request routing
● caching - some of
Example
libraryDependencies ++= {
val akkaV = "2.3.7"
val sprayV = "1.3.2"
Seq(
"com.typesafe.akka" %% "akka-actor" % akkaV,
"io.spray" %% "spray-can" % sprayV,
"io.spray" %% "spray-routing" % sprayV,
"io.spray" %% "spray-testkit" % sprayV % "test",
"org.scalatest" %% "scalatest" % "2.2.4" % "test")
}
Example
import scala.concurrent.duration._
import akka.actor.{Props, ActorSystem}
import akka.io.IO
import akka.pattern.ask
import akka.util.Timeout
import spray.can.Http
object App extends scala.App {
implicit val system = ActorSystem("system")
val service = system.actorOf( Props(new RestService), "rest")
implicit val timeout = Timeout(5.seconds)
IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080)
}
Example - not testable
import spray.routing.HttpServiceActor
class RestService extends HttpServiceActor {
def receive = runRoute(route)
def route =
get {
complete( "ok")
}
}
Example - extract trait
import spray.routing.HttpService
trait SimpleService extends HttpService {
def simpleRoute =
get {
complete( "ok")
}
}
Example - replace route
class RestService extends HttpServiceActor
with SimpleService {
def receive = runRoute(route)
def route =
simpleRoute
}
Example - test
import org.scalatest. {Matchers, FlatSpec}
import spray.testkit.ScalatestRouteTest
class SimpleServiceSpec extends FlatSpec with Matchers
with ScalatestRouteTest
with SimpleService {
def actorRefFactory = system // boilerplate
"A SimpleService" should "return 'ok' for GET request on /" in {
Get("/") ~> simpleRoute ~> check {
responseAs[ String] should be ("ok")
}
}
}
Test API
status.intValue
headers
responseAs[T] // (un)marshalling - String for free
rejections // little tricky when want to test deeper
Get("/users?format=pretty" )
Post("/user", """{"name": "pawel"}""" )
Put("/user/1", """{"name": "kopiczko"}""" )
Delete("/user/1")
Get("/mail/all") ~> Authorization(BasicHttpCredentials ("pawel", ""))
Test Rejection
def deleteRoute =
delete {
path("user" / IntNumber) { id =>
userService.delete(id)
complete( "Deleted user with id " + id)
}
}
Get("/user/1") ~> deleteRoute ~> check {
rejection should be ( MethodRejection (HttpMethods.DELETE))
}
OK, but...
Test Rejection
Get("/user/1") ~> deleteRoute ~> check {
status.intValue should be ( 405)
}
[info] - should not allow GET request on /user *** FAILED ***
[info] Request was rejected with List(MethodRejection(DELETE))
Test Rejection
Get("/user/1") ~> {
handleRejections( RejectionHandler .Default) {
deleteRoute
}
} ~> check {
status.intValue should be ( 405)
}
OK
Dependency Injection
Route is a method - pass arguments
def userRoute(service: UserService) =
get("user" / IntNumber) { id =>
complete {
userService.get(id)
}
}
Get("/user/1") ~> userRoute(userServiceMock) ~> check
Dependency Injection
● Test the REST layer responsibility
● Do NOT test underlying services
● There is another place for that
http://www.slideshare.net/kopiczko/scala45-spray-test-45539693
http://goo.gl/YuL3On

Weitere ähnliche Inhalte

Was ist angesagt?

Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleGeoff Ballinger
 
Hackathon presentation
Hackathon presentationHackathon presentation
Hackathon presentationDev Patel
 
Reactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsJohan Andrén
 
Prometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual TalksPrometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual TalksSatoshi Suzuki
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Johan Andrén
 
Distributed Eventing in OSGi
Distributed Eventing in OSGiDistributed Eventing in OSGi
Distributed Eventing in OSGiCarsten Ziegeler
 
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018Chris Gillum
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 LtShinichi Ogawa
 
From Zero to Stream Processing
From Zero to Stream ProcessingFrom Zero to Stream Processing
From Zero to Stream ProcessingEventador
 
Integration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container serviceIntegration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container serviceSaltStack
 
Retrofit
RetrofitRetrofit
Retrofitbresiu
 
OASGraph LoopBack 4 Integration
OASGraph LoopBack 4 IntegrationOASGraph LoopBack 4 Integration
OASGraph LoopBack 4 IntegrationMario Estrada
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackLove Nyberg
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with AkkaJohan Andrén
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for androidInnovationM
 

Was ist angesagt? (20)

Consul presentation
Consul presentationConsul presentation
Consul presentation
 
Airflow and supervisor
Airflow and supervisorAirflow and supervisor
Airflow and supervisor
 
Sharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's FinagleSharding and Load Balancing in Scala - Twitter's Finagle
Sharding and Load Balancing in Scala - Twitter's Finagle
 
Readme
ReadmeReadme
Readme
 
Hackathon presentation
Hackathon presentationHackathon presentation
Hackathon presentation
 
Reactive streams processing using Akka Streams
Reactive streams processing using Akka StreamsReactive streams processing using Akka Streams
Reactive streams processing using Akka Streams
 
Retrofit
RetrofitRetrofit
Retrofit
 
Prometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual TalksPrometheus meets Consul -- Consul Casual Talks
Prometheus meets Consul -- Consul Casual Talks
 
Reactive stream processing using Akka streams
Reactive stream processing using Akka streams Reactive stream processing using Akka streams
Reactive stream processing using Akka streams
 
Distributed Eventing in OSGi
Distributed Eventing in OSGiDistributed Eventing in OSGi
Distributed Eventing in OSGi
 
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
Advanced Durable Functions - Serverless Meetup Tokyo - Feb 2018
 
Appengine Java Night #2 Lt
Appengine Java Night #2 LtAppengine Java Night #2 Lt
Appengine Java Night #2 Lt
 
Parse Server Open Source
Parse Server Open SourceParse Server Open Source
Parse Server Open Source
 
From Zero to Stream Processing
From Zero to Stream ProcessingFrom Zero to Stream Processing
From Zero to Stream Processing
 
Integration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container serviceIntegration testing for salt states using aws ec2 container service
Integration testing for salt states using aws ec2 container service
 
Retrofit
RetrofitRetrofit
Retrofit
 
OASGraph LoopBack 4 Integration
OASGraph LoopBack 4 IntegrationOASGraph LoopBack 4 Integration
OASGraph LoopBack 4 Integration
 
Intelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStackIntelligent infrastructure with SaltStack
Intelligent infrastructure with SaltStack
 
Next generation actors with Akka
Next generation actors with AkkaNext generation actors with Akka
Next generation actors with Akka
 
Retrofit library for android
Retrofit library for androidRetrofit library for android
Retrofit library for android
 

Andere mochten auch

Water repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test methodWater repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test methodsrsujandiu
 
Water repellency of fabrics
Water repellency of fabricsWater repellency of fabrics
Water repellency of fabricsyousuf1234
 
Fabric tensile strength test
Fabric tensile strength testFabric tensile strength test
Fabric tensile strength testH.M. SIRAJ UDDIN
 
Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)Leonel Mayorga
 
Tema1. Introduccion molinux
Tema1. Introduccion molinuxTema1. Introduccion molinux
Tema1. Introduccion molinuxjpalencia
 
KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010Keller Williams Careers
 
Girsberger Benelux - Office collection
Girsberger Benelux - Office collectionGirsberger Benelux - Office collection
Girsberger Benelux - Office collectionArchitectura
 
CES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTICCES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTICEMOTIC
 
COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG TJVN2
 
U4 jou231 mobile_message
U4 jou231 mobile_messageU4 jou231 mobile_message
U4 jou231 mobile_messagepoole7
 
Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12 Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12 RoxanneGoins
 
Taskhero deck 10.15.12
Taskhero deck 10.15.12Taskhero deck 10.15.12
Taskhero deck 10.15.12taskhero
 
Programa #llopasfera14
Programa #llopasfera14Programa #llopasfera14
Programa #llopasfera14Llopa Sfera
 
BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010Dlamagna
 
06 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 1606 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 16UPyDNovelda
 
Bomba Dosadora Mroy
Bomba Dosadora MroyBomba Dosadora Mroy
Bomba Dosadora MroyVibropac
 

Andere mochten auch (20)

Water repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test methodWater repellency & waterproof & repellency test method
Water repellency & waterproof & repellency test method
 
Water repellency of fabrics
Water repellency of fabricsWater repellency of fabrics
Water repellency of fabrics
 
Fabric tensile strength test
Fabric tensile strength testFabric tensile strength test
Fabric tensile strength test
 
Dunya Paralari Gezgin
Dunya Paralari GezginDunya Paralari Gezgin
Dunya Paralari Gezgin
 
Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)Consejotecnicoescolarfaseintensiva20152016(2)
Consejotecnicoescolarfaseintensiva20152016(2)
 
Tema1. Introduccion molinux
Tema1. Introduccion molinuxTema1. Introduccion molinux
Tema1. Introduccion molinux
 
KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010KW Outfront Magazine Online Edition Sept/Oct 2010
KW Outfront Magazine Online Edition Sept/Oct 2010
 
Girsberger Benelux - Office collection
Girsberger Benelux - Office collectionGirsberger Benelux - Office collection
Girsberger Benelux - Office collection
 
CES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTICCES 2015 - Journée 1 vue par EMOTIC
CES 2015 - Journée 1 vue par EMOTIC
 
AguayoAbogados
AguayoAbogadosAguayoAbogados
AguayoAbogados
 
COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG COMO PUBLICAR ARCHIVOS EN EL BLOG
COMO PUBLICAR ARCHIVOS EN EL BLOG
 
U4 jou231 mobile_message
U4 jou231 mobile_messageU4 jou231 mobile_message
U4 jou231 mobile_message
 
Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12 Dragonslayer weekly update 17 aug 12
Dragonslayer weekly update 17 aug 12
 
Taskhero deck 10.15.12
Taskhero deck 10.15.12Taskhero deck 10.15.12
Taskhero deck 10.15.12
 
Programa #llopasfera14
Programa #llopasfera14Programa #llopasfera14
Programa #llopasfera14
 
BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010BB Family FB Group _ Jul -15-2010
BB Family FB Group _ Jul -15-2010
 
Angola cessaf final_2-3-2013
Angola cessaf final_2-3-2013Angola cessaf final_2-3-2013
Angola cessaf final_2-3-2013
 
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
Q7 es - Iniciativas locales de impulso a la innovación empresarial (ES)
 
06 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 1606 10-14 - acta pleno nº 16
06 10-14 - acta pleno nº 16
 
Bomba Dosadora Mroy
Bomba Dosadora MroyBomba Dosadora Mroy
Bomba Dosadora Mroy
 

Ähnlich wie Scala45 spray test

Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPdatamantra
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesScala Italy
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareAlona Mekhovova
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackChiradeep Vittal
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기NAVER D2
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsSagara Gunathunga
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js frameworkBen Lin
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Loiane Groner
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Max Lai
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Karel Minarik
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayMatthew Farwell
 
GraphQL API in Clojure
GraphQL API in ClojureGraphQL API in Clojure
GraphQL API in ClojureKent Ohashi
 

Ähnlich wie Scala45 spray test (20)

Building scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTPBuilding scalable rest service using Akka HTTP
Building scalable rest service using Akka HTTP
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
scalaphx-akka-http
scalaphx-akka-httpscalaphx-akka-http
scalaphx-akka-http
 
Federico Feroldi - Scala microservices
Federico Feroldi - Scala microservicesFederico Feroldi - Scala microservices
Federico Feroldi - Scala microservices
 
Using and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middlewareUsing and scaling Rack and Rack-based middleware
Using and scaling Rack and Rack-based middleware
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
StackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStackStackMate - CloudFormation for CloudStack
StackMate - CloudFormation for CloudStack
 
Spray human talks
Spray human talksSpray human talks
Spray human talks
 
[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기[245] presto 내부구조 파헤치기
[245] presto 내부구조 파헤치기
 
Java colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rsJava colombo-deep-dive-into-jax-rs
Java colombo-deep-dive-into-jax-rs
 
How and why i roll my own node.js framework
How and why i roll my own node.js frameworkHow and why i roll my own node.js framework
How and why i roll my own node.js framework
 
Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018Angular for Java Enterprise Developers: Oracle Code One 2018
Angular for Java Enterprise Developers: Oracle Code One 2018
 
Rack
RackRack
Rack
 
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅Java-Jersey 到 Python-Flask 服務不中斷重構之旅
Java-Jersey 到 Python-Flask 服務不中斷重構之旅
 
Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]Elasticsearch And Ruby [RuPy2012]
Elasticsearch And Ruby [RuPy2012]
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
 
Resthub lyonjug
Resthub lyonjugResthub lyonjug
Resthub lyonjug
 
Rack
RackRack
Rack
 
GraphQL API in Clojure
GraphQL API in ClojureGraphQL API in Clojure
GraphQL API in Clojure
 

Kürzlich hochgeladen

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 

Kürzlich hochgeladen (20)

Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 

Scala45 spray test

  • 2. The Plan ● What spray is ● What we are testing ● How
  • 3. Spray “an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka”
  • 4. Spray “an open-source toolkit for building REST/HTTP-based integration layers on top of Scala and Akka” Library to wrap services with REST API
  • 5. REST API ● request routing ● (un)marshalling to / from domain objects ● authentication / authorization ● encoding / decoding (compression) ● serving static content ● caching
  • 6. REST API ● request routing - headers, params and paths ● (un)marshalling to / from domain objects - req/resp entity ● authentication / authorization - directives ● encoding / decoding (compression) - Gzip, Deflate ● serving static content - the same way as request routing ● caching - some of
  • 7. Example libraryDependencies ++= { val akkaV = "2.3.7" val sprayV = "1.3.2" Seq( "com.typesafe.akka" %% "akka-actor" % akkaV, "io.spray" %% "spray-can" % sprayV, "io.spray" %% "spray-routing" % sprayV, "io.spray" %% "spray-testkit" % sprayV % "test", "org.scalatest" %% "scalatest" % "2.2.4" % "test") }
  • 8. Example import scala.concurrent.duration._ import akka.actor.{Props, ActorSystem} import akka.io.IO import akka.pattern.ask import akka.util.Timeout import spray.can.Http object App extends scala.App { implicit val system = ActorSystem("system") val service = system.actorOf( Props(new RestService), "rest") implicit val timeout = Timeout(5.seconds) IO(Http) ? Http.Bind(service, interface = "localhost", port = 8080) }
  • 9. Example - not testable import spray.routing.HttpServiceActor class RestService extends HttpServiceActor { def receive = runRoute(route) def route = get { complete( "ok") } }
  • 10. Example - extract trait import spray.routing.HttpService trait SimpleService extends HttpService { def simpleRoute = get { complete( "ok") } }
  • 11. Example - replace route class RestService extends HttpServiceActor with SimpleService { def receive = runRoute(route) def route = simpleRoute }
  • 12. Example - test import org.scalatest. {Matchers, FlatSpec} import spray.testkit.ScalatestRouteTest class SimpleServiceSpec extends FlatSpec with Matchers with ScalatestRouteTest with SimpleService { def actorRefFactory = system // boilerplate "A SimpleService" should "return 'ok' for GET request on /" in { Get("/") ~> simpleRoute ~> check { responseAs[ String] should be ("ok") } } }
  • 13. Test API status.intValue headers responseAs[T] // (un)marshalling - String for free rejections // little tricky when want to test deeper Get("/users?format=pretty" ) Post("/user", """{"name": "pawel"}""" ) Put("/user/1", """{"name": "kopiczko"}""" ) Delete("/user/1") Get("/mail/all") ~> Authorization(BasicHttpCredentials ("pawel", ""))
  • 14. Test Rejection def deleteRoute = delete { path("user" / IntNumber) { id => userService.delete(id) complete( "Deleted user with id " + id) } } Get("/user/1") ~> deleteRoute ~> check { rejection should be ( MethodRejection (HttpMethods.DELETE)) } OK, but...
  • 15. Test Rejection Get("/user/1") ~> deleteRoute ~> check { status.intValue should be ( 405) } [info] - should not allow GET request on /user *** FAILED *** [info] Request was rejected with List(MethodRejection(DELETE))
  • 16. Test Rejection Get("/user/1") ~> { handleRejections( RejectionHandler .Default) { deleteRoute } } ~> check { status.intValue should be ( 405) } OK
  • 17. Dependency Injection Route is a method - pass arguments def userRoute(service: UserService) = get("user" / IntNumber) { id => complete { userService.get(id) } } Get("/user/1") ~> userRoute(userServiceMock) ~> check
  • 18. Dependency Injection ● Test the REST layer responsibility ● Do NOT test underlying services ● There is another place for that