SlideShare a Scribd company logo
1 of 43
Download to read offline
©2013 DataStax Confidential. Do not distribute without consent.
@chbatey
Christopher Batey

Technical Evangelist for Apache Cassandra
LA 2015: Testing Cassandra applications
@chbatey
Who am I?
• Based in London
• Technical Evangelist for Apache Cassandra
•Work on Stubbed Cassandra
•Help out Apache Cassandra users
• Previous: Cassandra backed apps at BSkyB
@chbatey
Agenda
• Cassandra failure scenarios
• Developer tools
• Stubbed Cassandra
@chbatey
Production?
Application
@chbatey
Production?
ApplicationApplicationApplicationApplicationApplication
replication factor: 3
consistency: ONE
@chbatey
Production?
ApplicationApplicationApplicationApplicationApplication
ApplicationApplicationApplicationApplicationApplication
DC1
DC2
@chbatey
Read timeout
Application C
R1
R2
R3
C=QUROUM
Replication factor: 3
timeout
timeout
Read timeout
@chbatey
Read timeout
• Received acknowledgements
• Required acknowledgements
• Consistency level
• wasDataReceived
@chbatey
Write timeout
Application C
R1
R2
R3
C=QUROUM
Replication factor: 3
timeout
timeout
Write timeout
@chbatey
Retrying writes
• Cassandra does not roll back!
@chbatey
Write timeout
• Received acknowledgements
• Required acknowledgements
• Consistency level
• CAS and Batches are more complicated:
- WriteType: SIMPLE, BATCH, UNLOGGED_BATCH,
BATCH_LOG, CAS
@chbatey
Batches
• BATCH_LOG
- Timed out waiting for batch log replicas
- Retry if you like
• BATCH
- Written to batch log but timed out waiting for actual replica
- Will eventually be committed (serial read)
• UNLOGGED_BATCH
- Unknown - retry if you like
@chbatey
Idempotent writes
• All writes are idempotent with the following exceptions:
- Counters
- lists
@chbatey
Unavailable
Application C
R1
R2
R3
C=QUROUM
Replication factor: 3
Unavailable
@chbatey
Unavailable
• Alive Replicas
• Required Replicas
• Consistency
@chbatey
Coordinator issue
Application C
R1
R2
R3
C=QUROUM
Replication factor: 3
???
Set a socket read timeout!
@chbatey
Unit & Integration testing
• Requirements: Quick to run, deterministic, not brittle!!
• Integration tests against an embedded Cassandra?
• cassandra-unit
• Integration tests against an external Cassandra running on developer / CI
machines
• CCM
• Regular install
• Docker
• Vagrant
• Mocking the driver
@chbatey
Acceptance testing
Application
Acceptance
test
prepare data
verification
@chbatey
How do this if it was a HTTP service?
• Release it - great book
• Wiremock - mocking HTTP
services
• Saboteur - adding network
latency
If you want to build a fault tolerant application
you better test faults!
@chbatey
Stubbed Cassandra
Application
Acceptance
test
prime on admin port (REST)
verification on admin port
Admin endpoints
Native protocol
@chbatey
Two sides of Scassandra
• Java
-Acts as a unit/integration testing library
-90% of effort on this side
• Standalone
-Runs as a separate process
@chbatey
Java Client
• Embeds Stubbed Cassandra in a Java library
- Start / stop the server
- Prime the server to return rows and/or errors
- Verify exactly the queries your application has executed
@chbatey
Starting / Stopping
@ClassRule

public static final ScassandraServerRule SCASSANDRA = new
ScassandraServerRule();


Scassandra scassandra = ScassandraFactory.createServer();
scassandra.start();
PrimingClient primingClient = scassandra.primingClient();
ActivityClient activityClient = scassandra.activityClient();
@chbatey
Activity Client
• Query
‣ Query text
‣ Consistency
• PrepreparedStatementExecution
‣ Prepared statement text
‣ Bound variables


public List<Query> retrieveQueries();
public List<PreparedStatementExecution> retrievePreparedStatementExecutions()


public List<Connection> retrieveConnections();
public void clearAllRecordedActivity()


public void clearConnections();

public void clearQueries();

public void clearPreparedStatementExecutions();

@chbatey
Priming Client
• PrimingRequest
‣ Either a Query or PreparedStatement
‣ Query text or QueryPattern (regex)
‣ Consistency (default all)
‣ Result (success, read timeout, unavailable etc)
‣ Rows for successful response
‣ Column types for rows
‣ Variable types for prepared statements
public void prime(PrimingRequest prime)


public List<PrimingRequest> retrievePreparedPrimes()

public List<PrimingRequest> retrieveQueryPrimes()

public void clearAllPrimes()

public void clearQueryPrimes()

public void clearPreparedPrimes()





@chbatey
Example time
public interface PersonDao {

void connect();



void disconnect();



List<Person> retrievePeople();



List<Person> retrievePeopleByName(String firstName);



void storePerson(Person person);

}

@chbatey
Testing the connect method
@Test

public void shouldConnectToCassandraWhenConnectCalled() {

//given

activityClient.clearConnections();

//when

underTest.connect();

//then

assertTrue("Expected at least one connection",

activityClient.retrieveConnections().size() > 0);

}
@chbatey
Testing retrieve
public List<Person> retrieveNames() {

ResultSet result;

try {

Statement statement = new SimpleStatement("select * from person");

statement.setConsistencyLevel(ConsistencyLevel.QUORUM);

result = session.execute(statement);

} catch (ReadTimeoutException e) {

throw new UnableToRetrievePeopleException();

}



List<Person> people = new ArrayList<>();

for (Row row : result) {

people.add(new Person(row.getString("first_name"), row.getInt("age")));

}

return people;

}
@chbatey
Test the query + consistency
@Test

public void testQueryIssuedWithCorrectConsistencyUsingMatcher() {

//given

Query expectedQuery = Query.builder()

.withQuery("select * from person")

.withConsistency("QUORUM").build();



//when

underTest.retrievePeople();



//then

assertThat(activityClient.retrieveQueries(), containsQuery(expectedQuery));

}
Hamcrest matcher
@chbatey
Testing behaviour
@Test

public void testRetrievingOfNames() throws Exception {

// given

Map<String, ?> row = ImmutableMap.of(

"first_name", "Chris",

"last_name", "Batey",

"age", 29);

primingClient.prime(PrimingRequest.queryBuilder()

.withQuery("select * from person")

.withColumnTypes(column("age", PrimitiveType.INT))

.withRows(row)

.build());



//when

List<Person> names = underTest.retrievePeople();



//then

assertEquals(1, names.size());

assertEquals(“Chris Batey", names.get(0).getName());

}
Each Cassandra Row == Java map
Tell Scassandra about your schem
@chbatey
Testing errors
@Test(expected = UnableToRetrievePeopleException.class)

public void testHandlingOfReadRequestTimeout() throws Exception {

// given

PrimingRequest primeReadRequestTimeout = PrimingRequest.queryBuilder()

.withQuery("select * from person")

.withResult(Result.read_request_timeout)

.build();

primingClient.prime(primeReadRequestTimeout);



//when

underTest.retrievePeople();



//then

} Expecting custom exception
@chbatey
Testing retries


@Override

public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses,
int receivedResponses, boolean dataRetrieved, int nbRetry) {

if (nbRetry < configuredRetries) {

return RetryDecision.retry(cl);

} else {

return RetryDecision.rethrow();

}

}



@Override

public RetryDecision onWriteTimeout(Statement s, ConsistencyLevel cl, WriteType wt, int requiredAcks,
int receivedAcks, int nbRetry) {

return DefaultRetryPolicy.INSTANCE.onWriteTimeout(s, cl, wt, receivedAcks, receivedAcks, nbRetry);

}



@Override

public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica,
int aliveReplica, int nbRetry) {

return DefaultRetryPolicy.INSTANCE.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry);

}

@chbatey
Testing retries
@Test

public void testRetriesConfiguredNumberOfTimes() throws Exception {

PrimingRequest readTimeoutPrime = PrimingRequest.queryBuilder()

.withQuery("select * from person")

.withResult(Result.read_request_timeout)

.build();

primingClient.prime(readTimeoutPrime);



try {

underTest.retrievePeople();

} catch (UnableToRetrievePeopleException e) {

}



assertEquals(CONFIGURED_RETRIES + 1, activityClient.retrieveQueries().size());

}
@chbatey
Coordinator issue
Application C
R1
R2
R3
C=QUROUM
Replication factor: 3
???
@chbatey
Testing slow connection
@Test(expected = UnableToSavePersonException.class)

public void testThatSlowQueriesTimeout() throws Exception {

// given

PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()

.withQueryPattern("insert into person.*")

.withVariableTypes(VARCHAR, INT, list(TIMESTAMP))

.withFixedDelay(1000)

.build();

primingClient.prime(preparedStatementPrime);

underTest.connect();



underTest.storePerson(new Person("Christopher", 29, Collections.emptyList()));

}
Delays the response by 1000ms
Expect a custom exception
@chbatey
Testing slow connection
SocketOptions socketOptions = new SocketOptions();

socketOptions.setReadTimeoutMillis(500);

cluster = Cluster.builder()

.addContactPoint("localhost")

.withPort(port)

.withRetryPolicy(new RetryReads())

.withSocketOptions(socketOptions)

.build();
Set a read timeout
@Override

public void storePerson(Person person) {

try {

BoundStatement bind = storeStatement.bind(person.getName(), person.getAge());

session.execute(bind);

} catch (NoHostAvailableException e) {

throw new UnableToSavePersonException();

}

}
@chbatey
Summary of features
• Start as many instances as you like in the same JVM
• Prime all primitive types + collections
• Prime prepared statements
• Verify number of connections your application makes
• Test slow queries
@chbatey
Future features
• Loading of schema for priming prepared statements
• Pretending to be multiple nodes
@chbatey
How do I get it?
•It is on maven central
•Or go to www.scassandra.org
•Executable jar + REST API
<dependency>

<groupId>org.scassandra</groupId>

<artifactId>java-client</artifactId>

<version>0.6.0</version>

<scope>test</scope>

</dependency>
@chbatey
I want to help
• Server: https://github.com/scassandra/scassandra-
server
• Client: https://github.com/scassandra/scassandra-java-
client
• Tests: https://github.com/scassandra/scassandra-it-java-
driver-2
@chbatey
Summary
• Testing is good - I want more tools to help me
• Existing tools for Cassandra are great at happy path
scenarios
• Stubbed Cassandra allows testing of edge cases
@chbatey
The end - Questions?
www.scassandra.org
http://christopher-batey.blogspot.co.uk/
Ping me on twitter @chbatey
@chbatey
How does this work?
• Server implemented in Scala
• Binary port for your Cassandra application to connect to
• Admin port for the REST API
• Thin Java wrapper to make it easy to be used in JUnit
tests

More Related Content

What's hot

Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaMatt Stine
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayRoland Kuhn
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Codemotion
 
REEF: Towards a Big Data Stdlib
REEF: Towards a Big Data StdlibREEF: Towards a Big Data Stdlib
REEF: Towards a Big Data StdlibDataWorks Summit
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationSociable
 
NYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroNYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroChristopher Batey
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tKonrad Malawski
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesKonrad Malawski
 
Voxxed Vienna 2015 Fault tolerant microservices
Voxxed Vienna 2015 Fault tolerant microservicesVoxxed Vienna 2015 Fault tolerant microservices
Voxxed Vienna 2015 Fault tolerant microservicesChristopher Batey
 
HBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceHBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceKonrad Malawski
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsKonrad Malawski
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Konrad Malawski
 
Need for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsKonrad Malawski
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldKonrad Malawski
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
 
Manchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internalsManchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internalsChristopher Batey
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)Konrad Malawski
 

What's hot (20)

Reactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJavaReactive Fault Tolerant Programming with Hystrix and RxJava
Reactive Fault Tolerant Programming with Hystrix and RxJava
 
Reactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive WayReactive Streams: Handling Data-Flow the Reactive Way
Reactive Streams: Handling Data-Flow the Reactive Way
 
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
Samuele Resca - REACTIVE PROGRAMMING, DAMN. IT IS NOT ABOUT REACTJS - Codemot...
 
Resilience with Hystrix
Resilience with HystrixResilience with Hystrix
Resilience with Hystrix
 
REEF: Towards a Big Data Stdlib
REEF: Towards a Big Data StdlibREEF: Towards a Big Data Stdlib
REEF: Towards a Big Data Stdlib
 
Barcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentationBarcamp Auckland Rails3 presentation
Barcamp Auckland Rails3 presentation
 
NYC Cassandra Day - Java Intro
NYC Cassandra Day - Java IntroNYC Cassandra Day - Java Intro
NYC Cassandra Day - Java Intro
 
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in'tScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
ScalaSwarm 2017 Keynote: Tough this be madness yet theres method in't
 
Akka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutesAkka persistence == event sourcing in 30 minutes
Akka persistence == event sourcing in 30 minutes
 
Voxxed Vienna 2015 Fault tolerant microservices
Voxxed Vienna 2015 Fault tolerant microservicesVoxxed Vienna 2015 Fault tolerant microservices
Voxxed Vienna 2015 Fault tolerant microservices
 
HBase RowKey design for Akka Persistence
HBase RowKey design for Akka PersistenceHBase RowKey design for Akka Persistence
HBase RowKey design for Akka Persistence
 
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka StreamsFresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
Fresh from the Oven (04.2015): Experimental Akka Typed and Akka Streams
 
Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014Reactive Streams / Akka Streams - GeeCON Prague 2014
Reactive Streams / Akka Streams - GeeCON Prague 2014
 
Need for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applicationsNeed for Async: Hot pursuit for scalable applications
Need for Async: Hot pursuit for scalable applications
 
The Need for Async @ ScalaWorld
The Need for Async @ ScalaWorldThe Need for Async @ ScalaWorld
The Need for Async @ ScalaWorld
 
The things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and AkkaThe things we don't see – stories of Software, Scala and Akka
The things we don't see – stories of Software, Scala and Akka
 
Curator intro
Curator introCurator intro
Curator intro
 
Manchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internalsManchester Hadoop Meetup: Cassandra Spark internals
Manchester Hadoop Meetup: Cassandra Spark internals
 
Lambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter LawreyLambdas puzzler - Peter Lawrey
Lambdas puzzler - Peter Lawrey
 
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
[Tokyo Scala User Group] Akka Streams & Reactive Streams (0.7)
 

Similar to LA Cassandra Day 2015 - Testing Cassandra

Cassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsCassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsChristopher Batey
 
DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax Academy
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Christopher Batey
 
Cassandra Community Webinar - August 22 2013 - Cassandra Internals
Cassandra Community Webinar - August 22 2013 - Cassandra InternalsCassandra Community Webinar - August 22 2013 - Cassandra Internals
Cassandra Community Webinar - August 22 2013 - Cassandra Internalsaaronmorton
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in ScalaAlex Payne
 
An introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAn introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAjith Narayanan
 
Oracle real application clusters system tests with demo
Oracle real application clusters system tests with demoOracle real application clusters system tests with demo
Oracle real application clusters system tests with demoAjith Narayanan
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++Amazon Web Services
 
C* Summit EU 2013: Cassandra Internals
C* Summit EU 2013: Cassandra Internals C* Summit EU 2013: Cassandra Internals
C* Summit EU 2013: Cassandra Internals DataStax Academy
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net DriverDataStax Academy
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureSalesforce Developers
 
3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developersChristopher Batey
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherencearagozin
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaRick Warren
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiecturesIegor Fadieiev
 
Developing a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayJacob Park
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsDaniel Ballinger
 
Quarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationQuarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationCodeOps Technologies LLP
 

Similar to LA Cassandra Day 2015 - Testing Cassandra (20)

Cassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra ApplicationsCassandra Summit EU 2014 - Testing Cassandra Applications
Cassandra Summit EU 2014 - Testing Cassandra Applications
 
DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)DataStax: Making Cassandra Fail (for effective testing)
DataStax: Making Cassandra Fail (for effective testing)
 
Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?Cassandra is great but how do I test my application?
Cassandra is great but how do I test my application?
 
Cassandra Community Webinar - August 22 2013 - Cassandra Internals
Cassandra Community Webinar - August 22 2013 - Cassandra InternalsCassandra Community Webinar - August 22 2013 - Cassandra Internals
Cassandra Community Webinar - August 22 2013 - Cassandra Internals
 
Building Distributed Systems in Scala
Building Distributed Systems in ScalaBuilding Distributed Systems in Scala
Building Distributed Systems in Scala
 
Apache cassandra
Apache cassandraApache cassandra
Apache cassandra
 
An introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methodsAn introduction to_rac_system_test_planning_methods
An introduction to_rac_system_test_planning_methods
 
Oracle real application clusters system tests with demo
Oracle real application clusters system tests with demoOracle real application clusters system tests with demo
Oracle real application clusters system tests with demo
 
Shooting the Rapids
Shooting the RapidsShooting the Rapids
Shooting the Rapids
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
C* Summit EU 2013: Cassandra Internals
C* Summit EU 2013: Cassandra Internals C* Summit EU 2013: Cassandra Internals
C* Summit EU 2013: Cassandra Internals
 
Introduction to .Net Driver
Introduction to .Net DriverIntroduction to .Net Driver
Introduction to .Net Driver
 
Enhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock StructureEnhanced Web Service Testing: A Better Mock Structure
Enhanced Web Service Testing: A Better Mock Structure
 
3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers3 Dundee-Spark Overview for C* developers
3 Dundee-Spark Overview for C* developers
 
Performance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle CoherencePerformance Test Driven Development with Oracle Coherence
Performance Test Driven Development with Oracle Coherence
 
Building Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJavaBuilding Scalable Stateless Applications with RxJava
Building Scalable Stateless Applications with RxJava
 
Serverless archtiectures
Serverless archtiecturesServerless archtiectures
Serverless archtiectures
 
Developing a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and SprayDeveloping a Real-time Engine with Akka, Cassandra, and Spray
Developing a Real-time Engine with Akka, Cassandra, and Spray
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Quarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java ApplicationQuarkus - a shrink ray to your Java Application
Quarkus - a shrink ray to your Java Application
 

More from Christopher Batey

Docker and jvm. A good idea?
Docker and jvm. A good idea?Docker and jvm. A good idea?
Docker and jvm. A good idea?Christopher Batey
 
LJC: Microservices in the real world
LJC: Microservices in the real worldLJC: Microservices in the real world
LJC: Microservices in the real worldChristopher Batey
 
Cassandra Day NYC - Cassandra anti patterns
Cassandra Day NYC - Cassandra anti patternsCassandra Day NYC - Cassandra anti patterns
Cassandra Day NYC - Cassandra anti patternsChristopher Batey
 
Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!Christopher Batey
 
Cassandra London - 2.2 and 3.0
Cassandra London - 2.2 and 3.0Cassandra London - 2.2 and 3.0
Cassandra London - 2.2 and 3.0Christopher Batey
 
Cassandra London - C* Spark Connector
Cassandra London - C* Spark ConnectorCassandra London - C* Spark Connector
Cassandra London - C* Spark ConnectorChristopher Batey
 
Paris Day Cassandra: Use case
Paris Day Cassandra: Use caseParis Day Cassandra: Use case
Paris Day Cassandra: Use caseChristopher Batey
 
Dublin Meetup: Cassandra anti patterns
Dublin Meetup: Cassandra anti patternsDublin Meetup: Cassandra anti patterns
Dublin Meetup: Cassandra anti patternsChristopher Batey
 
Cassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsCassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsChristopher Batey
 
Data Science Lab Meetup: Cassandra and Spark
Data Science Lab Meetup: Cassandra and SparkData Science Lab Meetup: Cassandra and Spark
Data Science Lab Meetup: Cassandra and SparkChristopher Batey
 
Manchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationManchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationChristopher Batey
 
Manchester Hadoop User Group: Cassandra Intro
Manchester Hadoop User Group: Cassandra IntroManchester Hadoop User Group: Cassandra Intro
Manchester Hadoop User Group: Cassandra IntroChristopher Batey
 
Webinar Cassandra Anti-Patterns
Webinar Cassandra Anti-PatternsWebinar Cassandra Anti-Patterns
Webinar Cassandra Anti-PatternsChristopher Batey
 
Munich March 2015 - Cassandra + Spark Overview
Munich March 2015 -  Cassandra + Spark OverviewMunich March 2015 -  Cassandra + Spark Overview
Munich March 2015 - Cassandra + Spark OverviewChristopher Batey
 
Reading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkReading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkChristopher Batey
 
LA Cassandra Day 2015 - Cassandra for developers
LA Cassandra Day 2015  - Cassandra for developersLA Cassandra Day 2015  - Cassandra for developers
LA Cassandra Day 2015 - Cassandra for developersChristopher Batey
 

More from Christopher Batey (20)

Cassandra summit LWTs
Cassandra summit  LWTsCassandra summit  LWTs
Cassandra summit LWTs
 
Docker and jvm. A good idea?
Docker and jvm. A good idea?Docker and jvm. A good idea?
Docker and jvm. A good idea?
 
LJC: Microservices in the real world
LJC: Microservices in the real worldLJC: Microservices in the real world
LJC: Microservices in the real world
 
Cassandra Day NYC - Cassandra anti patterns
Cassandra Day NYC - Cassandra anti patternsCassandra Day NYC - Cassandra anti patterns
Cassandra Day NYC - Cassandra anti patterns
 
Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!Think your software is fault-tolerant? Prove it!
Think your software is fault-tolerant? Prove it!
 
Cassandra London - 2.2 and 3.0
Cassandra London - 2.2 and 3.0Cassandra London - 2.2 and 3.0
Cassandra London - 2.2 and 3.0
 
Cassandra London - C* Spark Connector
Cassandra London - C* Spark ConnectorCassandra London - C* Spark Connector
Cassandra London - C* Spark Connector
 
IoT London July 2015
IoT London July 2015IoT London July 2015
IoT London July 2015
 
1 Dundee - Cassandra 101
1 Dundee - Cassandra 1011 Dundee - Cassandra 101
1 Dundee - Cassandra 101
 
2 Dundee - Cassandra-3
2 Dundee - Cassandra-32 Dundee - Cassandra-3
2 Dundee - Cassandra-3
 
Paris Day Cassandra: Use case
Paris Day Cassandra: Use caseParis Day Cassandra: Use case
Paris Day Cassandra: Use case
 
Dublin Meetup: Cassandra anti patterns
Dublin Meetup: Cassandra anti patternsDublin Meetup: Cassandra anti patterns
Dublin Meetup: Cassandra anti patterns
 
Cassandra Day London: Building Java Applications
Cassandra Day London: Building Java ApplicationsCassandra Day London: Building Java Applications
Cassandra Day London: Building Java Applications
 
Data Science Lab Meetup: Cassandra and Spark
Data Science Lab Meetup: Cassandra and SparkData Science Lab Meetup: Cassandra and Spark
Data Science Lab Meetup: Cassandra and Spark
 
Manchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra IntegrationManchester Hadoop Meetup: Spark Cassandra Integration
Manchester Hadoop Meetup: Spark Cassandra Integration
 
Manchester Hadoop User Group: Cassandra Intro
Manchester Hadoop User Group: Cassandra IntroManchester Hadoop User Group: Cassandra Intro
Manchester Hadoop User Group: Cassandra Intro
 
Webinar Cassandra Anti-Patterns
Webinar Cassandra Anti-PatternsWebinar Cassandra Anti-Patterns
Webinar Cassandra Anti-Patterns
 
Munich March 2015 - Cassandra + Spark Overview
Munich March 2015 -  Cassandra + Spark OverviewMunich March 2015 -  Cassandra + Spark Overview
Munich March 2015 - Cassandra + Spark Overview
 
Reading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache SparkReading Cassandra Meetup Feb 2015: Apache Spark
Reading Cassandra Meetup Feb 2015: Apache Spark
 
LA Cassandra Day 2015 - Cassandra for developers
LA Cassandra Day 2015  - Cassandra for developersLA Cassandra Day 2015  - Cassandra for developers
LA Cassandra Day 2015 - Cassandra for developers
 

Recently uploaded

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfYashikaSharma391629
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 

Recently uploaded (20)

Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdfInnovate and Collaborate- Harnessing the Power of Open Source Software.pdf
Innovate and Collaborate- Harnessing the Power of Open Source Software.pdf
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 

LA Cassandra Day 2015 - Testing Cassandra

  • 1. ©2013 DataStax Confidential. Do not distribute without consent. @chbatey Christopher Batey
 Technical Evangelist for Apache Cassandra LA 2015: Testing Cassandra applications
  • 2. @chbatey Who am I? • Based in London • Technical Evangelist for Apache Cassandra •Work on Stubbed Cassandra •Help out Apache Cassandra users • Previous: Cassandra backed apps at BSkyB
  • 3. @chbatey Agenda • Cassandra failure scenarios • Developer tools • Stubbed Cassandra
  • 8. @chbatey Read timeout • Received acknowledgements • Required acknowledgements • Consistency level • wasDataReceived
  • 11. @chbatey Write timeout • Received acknowledgements • Required acknowledgements • Consistency level • CAS and Batches are more complicated: - WriteType: SIMPLE, BATCH, UNLOGGED_BATCH, BATCH_LOG, CAS
  • 12. @chbatey Batches • BATCH_LOG - Timed out waiting for batch log replicas - Retry if you like • BATCH - Written to batch log but timed out waiting for actual replica - Will eventually be committed (serial read) • UNLOGGED_BATCH - Unknown - retry if you like
  • 13. @chbatey Idempotent writes • All writes are idempotent with the following exceptions: - Counters - lists
  • 15. @chbatey Unavailable • Alive Replicas • Required Replicas • Consistency
  • 17. @chbatey Unit & Integration testing • Requirements: Quick to run, deterministic, not brittle!! • Integration tests against an embedded Cassandra? • cassandra-unit • Integration tests against an external Cassandra running on developer / CI machines • CCM • Regular install • Docker • Vagrant • Mocking the driver
  • 19. @chbatey How do this if it was a HTTP service? • Release it - great book • Wiremock - mocking HTTP services • Saboteur - adding network latency If you want to build a fault tolerant application you better test faults!
  • 20. @chbatey Stubbed Cassandra Application Acceptance test prime on admin port (REST) verification on admin port Admin endpoints Native protocol
  • 21. @chbatey Two sides of Scassandra • Java -Acts as a unit/integration testing library -90% of effort on this side • Standalone -Runs as a separate process
  • 22. @chbatey Java Client • Embeds Stubbed Cassandra in a Java library - Start / stop the server - Prime the server to return rows and/or errors - Verify exactly the queries your application has executed
  • 23. @chbatey Starting / Stopping @ClassRule
 public static final ScassandraServerRule SCASSANDRA = new ScassandraServerRule(); 
 Scassandra scassandra = ScassandraFactory.createServer(); scassandra.start(); PrimingClient primingClient = scassandra.primingClient(); ActivityClient activityClient = scassandra.activityClient();
  • 24. @chbatey Activity Client • Query ‣ Query text ‣ Consistency • PrepreparedStatementExecution ‣ Prepared statement text ‣ Bound variables 
 public List<Query> retrieveQueries(); public List<PreparedStatementExecution> retrievePreparedStatementExecutions() 
 public List<Connection> retrieveConnections(); public void clearAllRecordedActivity() 
 public void clearConnections();
 public void clearQueries();
 public void clearPreparedStatementExecutions();

  • 25. @chbatey Priming Client • PrimingRequest ‣ Either a Query or PreparedStatement ‣ Query text or QueryPattern (regex) ‣ Consistency (default all) ‣ Result (success, read timeout, unavailable etc) ‣ Rows for successful response ‣ Column types for rows ‣ Variable types for prepared statements public void prime(PrimingRequest prime) 
 public List<PrimingRequest> retrievePreparedPrimes()
 public List<PrimingRequest> retrieveQueryPrimes()
 public void clearAllPrimes()
 public void clearQueryPrimes()
 public void clearPreparedPrimes()
 
 

  • 26. @chbatey Example time public interface PersonDao {
 void connect();
 
 void disconnect();
 
 List<Person> retrievePeople();
 
 List<Person> retrievePeopleByName(String firstName);
 
 void storePerson(Person person);
 }

  • 27. @chbatey Testing the connect method @Test
 public void shouldConnectToCassandraWhenConnectCalled() {
 //given
 activityClient.clearConnections();
 //when
 underTest.connect();
 //then
 assertTrue("Expected at least one connection",
 activityClient.retrieveConnections().size() > 0);
 }
  • 28. @chbatey Testing retrieve public List<Person> retrieveNames() {
 ResultSet result;
 try {
 Statement statement = new SimpleStatement("select * from person");
 statement.setConsistencyLevel(ConsistencyLevel.QUORUM);
 result = session.execute(statement);
 } catch (ReadTimeoutException e) {
 throw new UnableToRetrievePeopleException();
 }
 
 List<Person> people = new ArrayList<>();
 for (Row row : result) {
 people.add(new Person(row.getString("first_name"), row.getInt("age")));
 }
 return people;
 }
  • 29. @chbatey Test the query + consistency @Test
 public void testQueryIssuedWithCorrectConsistencyUsingMatcher() {
 //given
 Query expectedQuery = Query.builder()
 .withQuery("select * from person")
 .withConsistency("QUORUM").build();
 
 //when
 underTest.retrievePeople();
 
 //then
 assertThat(activityClient.retrieveQueries(), containsQuery(expectedQuery));
 } Hamcrest matcher
  • 30. @chbatey Testing behaviour @Test
 public void testRetrievingOfNames() throws Exception {
 // given
 Map<String, ?> row = ImmutableMap.of(
 "first_name", "Chris",
 "last_name", "Batey",
 "age", 29);
 primingClient.prime(PrimingRequest.queryBuilder()
 .withQuery("select * from person")
 .withColumnTypes(column("age", PrimitiveType.INT))
 .withRows(row)
 .build());
 
 //when
 List<Person> names = underTest.retrievePeople();
 
 //then
 assertEquals(1, names.size());
 assertEquals(“Chris Batey", names.get(0).getName());
 } Each Cassandra Row == Java map Tell Scassandra about your schem
  • 31. @chbatey Testing errors @Test(expected = UnableToRetrievePeopleException.class)
 public void testHandlingOfReadRequestTimeout() throws Exception {
 // given
 PrimingRequest primeReadRequestTimeout = PrimingRequest.queryBuilder()
 .withQuery("select * from person")
 .withResult(Result.read_request_timeout)
 .build();
 primingClient.prime(primeReadRequestTimeout);
 
 //when
 underTest.retrievePeople();
 
 //then
 } Expecting custom exception
  • 32. @chbatey Testing retries 
 @Override
 public RetryDecision onReadTimeout(Statement statement, ConsistencyLevel cl, int requiredResponses, int receivedResponses, boolean dataRetrieved, int nbRetry) {
 if (nbRetry < configuredRetries) {
 return RetryDecision.retry(cl);
 } else {
 return RetryDecision.rethrow();
 }
 }
 
 @Override
 public RetryDecision onWriteTimeout(Statement s, ConsistencyLevel cl, WriteType wt, int requiredAcks, int receivedAcks, int nbRetry) {
 return DefaultRetryPolicy.INSTANCE.onWriteTimeout(s, cl, wt, receivedAcks, receivedAcks, nbRetry);
 }
 
 @Override
 public RetryDecision onUnavailable(Statement statement, ConsistencyLevel cl, int requiredReplica, int aliveReplica, int nbRetry) {
 return DefaultRetryPolicy.INSTANCE.onUnavailable(statement, cl, requiredReplica, aliveReplica, nbRetry);
 }

  • 33. @chbatey Testing retries @Test
 public void testRetriesConfiguredNumberOfTimes() throws Exception {
 PrimingRequest readTimeoutPrime = PrimingRequest.queryBuilder()
 .withQuery("select * from person")
 .withResult(Result.read_request_timeout)
 .build();
 primingClient.prime(readTimeoutPrime);
 
 try {
 underTest.retrievePeople();
 } catch (UnableToRetrievePeopleException e) {
 }
 
 assertEquals(CONFIGURED_RETRIES + 1, activityClient.retrieveQueries().size());
 }
  • 35. @chbatey Testing slow connection @Test(expected = UnableToSavePersonException.class)
 public void testThatSlowQueriesTimeout() throws Exception {
 // given
 PrimingRequest preparedStatementPrime = PrimingRequest.preparedStatementBuilder()
 .withQueryPattern("insert into person.*")
 .withVariableTypes(VARCHAR, INT, list(TIMESTAMP))
 .withFixedDelay(1000)
 .build();
 primingClient.prime(preparedStatementPrime);
 underTest.connect();
 
 underTest.storePerson(new Person("Christopher", 29, Collections.emptyList()));
 } Delays the response by 1000ms Expect a custom exception
  • 36. @chbatey Testing slow connection SocketOptions socketOptions = new SocketOptions();
 socketOptions.setReadTimeoutMillis(500);
 cluster = Cluster.builder()
 .addContactPoint("localhost")
 .withPort(port)
 .withRetryPolicy(new RetryReads())
 .withSocketOptions(socketOptions)
 .build(); Set a read timeout @Override
 public void storePerson(Person person) {
 try {
 BoundStatement bind = storeStatement.bind(person.getName(), person.getAge());
 session.execute(bind);
 } catch (NoHostAvailableException e) {
 throw new UnableToSavePersonException();
 }
 }
  • 37. @chbatey Summary of features • Start as many instances as you like in the same JVM • Prime all primitive types + collections • Prime prepared statements • Verify number of connections your application makes • Test slow queries
  • 38. @chbatey Future features • Loading of schema for priming prepared statements • Pretending to be multiple nodes
  • 39. @chbatey How do I get it? •It is on maven central •Or go to www.scassandra.org •Executable jar + REST API <dependency>
 <groupId>org.scassandra</groupId>
 <artifactId>java-client</artifactId>
 <version>0.6.0</version>
 <scope>test</scope>
 </dependency>
  • 40. @chbatey I want to help • Server: https://github.com/scassandra/scassandra- server • Client: https://github.com/scassandra/scassandra-java- client • Tests: https://github.com/scassandra/scassandra-it-java- driver-2
  • 41. @chbatey Summary • Testing is good - I want more tools to help me • Existing tools for Cassandra are great at happy path scenarios • Stubbed Cassandra allows testing of edge cases
  • 42. @chbatey The end - Questions? www.scassandra.org http://christopher-batey.blogspot.co.uk/ Ping me on twitter @chbatey
  • 43. @chbatey How does this work? • Server implemented in Scala • Binary port for your Cassandra application to connect to • Admin port for the REST API • Thin Java wrapper to make it easy to be used in JUnit tests