concept test in category scala

appears as: tests, test, test, tests, The test
Reactive Design Patterns

This is an excerpt from Manning's book Reactive Design Patterns.

Of course, we should stay away from abuses of anthropomorphism: we are slowly eliminating terminology like “master/slave” in recognition that not everybody takes the technical context into account when interpreting them.[15] But even responsible use offers plentiful opportunities for spicing up possibly dull work a little: for example, by calling a component responsible for writing logs to disk a Scribe. Implementing that class will have the feel of creating a little robot that will do certain things you tell it to and with which you can play a bit—others call that activity writing tests and make a sour face while saying so. With Reactive programming, you can turn this around and realize: it’s fun!

This will check every 50 ms whether the Future has received its value or was completed with an error, not letting the test continue before one or the other occurs. The syntax used is that of scala.concurrent.Future; in other implementations, the name of the status query method could be isDone() (java.util.concurrent.Future), isPending() (JavaScript Q), or inspect() (JavaScript when), to name a few examples. In a real test procedure, the number of loop iterations must be bounded:

var i = 20
while (!future.isCompleted && i > 0) {
  i -= 1
  Thread.sleep(50)
}
if (i == 0) fail("translation was not received in time")

This will wait only for up to roughly 1 second and fail the test if the Future is not completed within that time window. Otherwise, message loss or a programming error could lead to the Future never receiving a value; then the test procedure would hang and never yield a result.

The first step toward fixing this was taken when you devised an Actor to verify the response latency characteristics of EchoService. ParallelSLATester is a fully Reactive component that you developed to test a characteristic of another Reactive component. The only incongruous piece in that test was the synchronous procedure used to start the test and await the result. What you would like to write instead is the following.

Listing 11.13. Handling responses asynchronously to create fully Reactive tests
val echo = echoService() val N = 10000 val maxParallelism = 500 val controller = system.actorOf(Props[ParallelSLATester],                                 "keepSLAparallelController") val future = controller ? TestSLA(echo, N, maxParallelism, _) for (SLAResponse(timings, outstanding) <- future) yield {   val sorted = result.timings.sorted   val ninetyfifthPercentile = sorted.dropRight(N * 5 / 100).last #1   ninetyfifthPercentile should be < 2.milliseconds } #1 - Discards the top 5%

Here, you initiate the test by sending the TestSLA command to the Actor, using the Ask pattern to get back a Future for the later reply. You then transform that Future to perform the calculation and verification of the latency profile, resulting in a Future that will either be successful or fail, depending on the outcome of the assertion in the next-to-last line. In traditional testing frameworks, this Future will not be inspected, making this approach futile. An asynchronous testing framework, on the other hand, will react to the completion of this Future in order to determine whether the test was successful.

Most synchronous test procedures verify that a certain sequence of actions results in a given sequence of results: set up the translation service, invoke it, and compare the returned value to the expected one. This means the aspect of time does not play a role in these tests: the test result will not depend on whether running the test is a matter of milliseconds or takes a few hours. The basic assumption is that all processing occurs in the context of the test procedure, literally beneath its frame of control. Therefore, it is enough to react to returned values or thrown exceptions. There will always be a result—infinite loops will be noticed eventually by the human observer.

In an asynchronous system, this assumption no longer holds: it is possible that the execution of the module under test occurs far removed from the test procedure, and replies may not only arrive late, they can also be lost. The latter can be due to programming errors (not sending a reply message, not fulfilling a Promise in some edge case, and so on), or it can be due to failures like message loss on the network or resource exhaustion—if an asynchronous task cannot be enqueued to be run, then its result will never be computed.

For this reason, it is unwise to wait indefinitely for replies during test procedures, because you do not want the entire test run to grind to a halt halfway through just because of one lost message. You need to place an upper bound on waiting times, fail tests that violate it, and move on.

Figure 11.2. The test procedure initiates multiple calls to the service under test, which may be executed in parallel; aggregates the timings; and verifies that the SLA is met.
sbt in Action

This is an excerpt from Manning's book sbt in Action.

  • A number of built-in tasks (test, compile, publish)
  • Figure 3.4. To write a test for your new project, you added the specs2 testing library.

    As you can see, this is quite a lot of setup for the tests that you have, but if you had more tests, it would become more worth it. If you were playing along at home, you would have noticed a few things when you executed the tests.

    The first, most obvious, is that the tests are quite slow to execute, at least compared to the normal unit test cycle. This becomes especially painful if you’re using the add test/develop cycle that you used in the previous section.

    Second, you can actually interact with the browser started by the tests during the tests. You can close it. This, not surprisingly, causes the tests to fail.

    Third, for the Windows users among you, when you run this on a Windows machine, you get a UAC warning from Windows every time you start the chromeserver. UAC stands for User Account Control. Basically, it’s warning you that you’re about to do something that requires administrator privileges. It’s generally a bad idea to disable these kinds of security checks, but they do interrupt the workflow because you have to click on the warning to allow the tests to continue.

    specs2 can generate an HTML report of the tests you’ve run, so you’ll use that as a basis of your reports. First you need to generate the HTML; this is done by specifying the html option to specs2 in build.sbt:

    testOptions in Test += Tests.Argument("html")
    Scala in Action

    This is an excerpt from Manning's book Scala in Action.

    This sample client creates a database called mydb and prints the names of all the collections under the database. If you run the code, it will print test and system.indexes, because by default MongoDB creates these two collections for you.

    So far, I’ve been showing you code without writing tests—so why worry about that right now? The answer is, I wrote tests around the code but didn’t mention doing so because I wanted you to focus more on the Scala language. Now that’s going to change. My goal for this chapter is to make you comfortable writing automated tests in Scala so that you can build production-quality software.

    The path to writing well-crafted code[1] is the path where you write tests for your code. The common perception about writing tests is that it’s hard, but this chapter will change that mindset. I’m going to show you how you can get started with practices like test-driven development and continuous integration for your Scala project. The idea of test-driven development (TDD) is to write the test before you write code. I know this seems backward, but I promise you that by the end of this chapter it will make sense. You’ll learn that writing tests is more like doing a design exercise than testing, and it makes sense to design your software. Your design tool will be code—more specifically, test code.

    In the case of the TestPricingSystem, the calculators are implemented using TestDouble so that it helps to write tests around the calculate price service. In your tests you’ll use the TestPricingSystem shown in the following listing.

    Listing 10.4. JUnit test case for calculating price service (cake pattern)

    You mix the test version of the pricing system into your test class. This will automatically make the fake implementation of the calculators available inside the test. That simplifies your test and lets you focus testing on the CalculatePriceService. The two tests are testing whether the CalculatePriceService is using the right type of calculator when invoked with the name of the calculator.

    This is a standard version of a Spring configuration file, where the calculators and the CalculatePriceService are defined by setting up the dependencies . Save this Spring application-context.xml file in your src/main/resources folder in your SBT project. This is the main configuration file for the pricing application. This file will be used to initialize the application beans. Similarly, you also have a test version of the configuration file under src/test/resources that refers to the fake implementation of calculators. You could also create fake instances inside the test and inject them. You’ll use the latter one to see how you could inject fake versions of the calculators. But first add the following dependencies to your SBT project file:

    To test CalculatePriceService, you can use Spring to configure the beans and override the appropriate calculator inside the test. To use Spring with the JUnit test, add the following annotations along with the test class declaration:

    @RunWith(classOf[SpringJUnit4ClassRunner])
    @ContextConfiguration(
         locations = Array("classpath:/application-context.xml"))

    The RunWith annotation allows JUnit tests to get access to instantiated beans as defined in the application context file. The ContextConfiguration lets you specify which configuration file to use to initialize beans. If you have a test version of the configuration file, specify that. Inside the test, if you declare a variable of CalculatePriceService with the @Resource annotation, Spring will create and inject an instance of it into the test. Here’s the skeleton JUnit test with Spring configuration:

    @RunWith(classOf[SpringJUnit4ClassRunner])
    @ContextConfiguration(locations =
         Array("classpath:/application-context.xml"))
    class CalculatePriceServiceTest {
    
      @Resource
      var calculatePriceService: CalculatePriceService = _
    }

    The instance of CalculatePriceService will be created by the Spring framework and injected inside the test for you. At this point, this test class is set up for testing the calculate price service. The following is the JUnit test to check that the calculate price service uses the cost-plus calculator to calculate price:

    @Test
    def shouldUseCostPlusCalculatorWhenPriceTypeIsCostPlus() {
      val fakeCostPlusCalculator = new Calculator {
        def calculate(productId: String) = 2.0D
      }
      calculatePriceService.setCostPlusCalculator(fakeCostPlusCalculator)
      val price = calculatePriceService.calculate("costPlus", "some product")
      assertEquals(2.0D, price)
    }

    The real implementation of the costPlusCalculator is replaced by a fake implementation. The test is passing "costPlus" as a price type, and according to the logic (see listing 10.5) it will use the cost-plus calculator. Similarly, the following is the test for an external price source calculator: