Archive: 2015

Unit testing an AngularJS directive's private functions.

Posted on by  
Richard Rijnberk

As we all know Javascript gives us the awesome ability to create functions inside functions. This allows us to create private functions which support the main function. It is also something we do often when creating object functions. This structure is used by angular for the creation of providers and directives alike. Every once in a while I personally come to a point where I would like to test these private functions. This is especially true for use cases in Angular such as directives.I'd like to be able to run unit tests for a directive's private functions, but I'd like to do this without having to make them public. The way I do this is by using a concept called reflection. This process actually described by Bob Gravelle in his post 'Accessing Private functions in Javascript' actually exposes the private functions by using the toString method of a function. Before I go into specifics let me say that this article should only be used as an approach  for unit testing. There is a good reason for keeping private functions private and using this concept for application code may very well introduce interesting side effects. That being said let's go into details. In order for us to use this concept we'll need to make some slight changes to our directive. Normally we would declare our Directive Definition Object (DDO) and directly return it. As below:

return {
  restrict: 'E'
  ...
}

Continue reading →

Geb Gems: Handling AJAX requests

Posted on by  
Albert van Veen

One of the biggest struggles while testing web applications that use AJAX is dealing with the timing issues caused by asynchronous nature of the request. A common solution is using timeouts to wait for the AJAX call to be completed. This could cause lots of timing issues. Using Geb there is a better way to determine that the AJAX call and its callback has been completed.

In this blog post we will test the W3Schools website which has a button on it which executes an AJAX request: http://www.w3schools.com/ajax/ajax_example.asp

Continue reading →

NextBuild 2015 Conference Report

Posted on by  
Hubert Klein Ikkink

Saturday May 30th was the first NextBuild developer's conference in Eindhoven at the High Tech Campus. The conference is free for attendees and offers a variety of subjects presented by colleague developer's. This meant all talks were very practical and covered subjects encountered in real projects. This adds real value for me to attend a talk. Although it was on a weekend day there were about 150 attendees present. The location was very nice and allowed for a nice, informal atmosphere with a lot of opportunities to catch up.

The day started with a key note talk by Alex Sinner of Amazon. He looked into microservices and explained the features of AWS and especially the container support and the new AWS Lambda service. With the AWS Lambda service we can deploy functions that are executed on the Amazon infrastructure and we only pay when such a function needs to be executed. After the keynote the conference tracks were separated into five rooms, so sometimes it was difficult to choose a track. I went to the talk by my JDriven colleague Rob Brinkman about a Westy tracking platform he built with Vert.x, Groovy, AngularJS, Redis, Docker and Gradle. For those that don't know, but a Westy is a Volkswagen van used for camping trips. Rob has build a platform where a (cheap) tracker unit communicates to a Vert.x module the location of the Westy. This is all combined with other trip details and information in a web application. Every works with push events and the information is updated in real time in the web application. The talks was very interesting and really shows also the power and elegance of Vert.x. Also the architecture provided is a like a blueprint for Internet of Things (IoT) applications.

Continue reading →

Validating input in Spray

Posted on by  
Tammo Sminia

In Spray, you get a lot of input validations for free. If you have a model like this:

object RobotProtocol extends DefaultJsonProtocol {
  case class Robot(name: String, amountOfArms: Int)
  implicit val RobotFormat = jsonFormat2(Robot)
}

Continue reading →

Groovy Goodness: Share Data in Concurrent Environment with Dataflow Variables

Posted on by  
Hubert Klein Ikkink

To work with data in a concurrent environment can be complex. Groovy includes GPars, yes we don't have to download any dependencies, to provide some models to work easily with data in a concurrent environment. In this blog post we are going to look at an example where we use dataflow variables to exchange data between concurrent tasks. In a dataflow algorithm we define certain functions or tasks that have an input and output. A task is started when the input is available for the task. So instead of defining an imperative sequence of tasks that need to be executed, we define a series of tasks that will start executing when their input is available. And the nice thing is that each of these tasks are independent and can run in parallel if needed.
The data that is shared between tasks is stored in dataflow variables. The value of a dataflow variable can only be set once, but it can be read multiple times. When a task wants to read the value, but it is not yet available, the task will wait for the value in a non-blocking way.

In the following example Groovy script we use the Dataflows class. This class provides an easy way to set multiple dataflow variables and get their values. In the script we want to get the temperature in a city in both Celcius and Fahrenheit and we are using remote web services to the data:

Continue reading →

Grails Goodness: Custom Data Binding with @DataBinding Annotation

Posted on by  
Hubert Klein Ikkink

Grails has a data binding mechanism that will convert request parameters to properties of an object of different types. We can customize the default data binding in different ways. One of them is using the @DataBinding annotation. We use a closure as argument for the annotation in which we must return the converted value. We get two arguments, the first is the object the data binding is applied to and the second is the source with all original values of type SimpleMapDataBindingSource. The source could for example be a map like structure or the parameters of a request object.

In the next example code we have a Product class with a ProductId class. We write a custom data binding to convert the String value with the pattern {code}-{identifier} to a ProductId object:

Continue reading →

Geb Gems: Using Pages and Modules

Posted on by  
Albert van Veen

In the previous blog post about Geb, we have been introduced to the Geb Framework. In this blogpost we will be introduced to Pages and Modules. A Page represents a specific page from a web application. A module represent a part of the page; for example a sign-up form, a menu bar or contact form. Pages and Modules are very useful since they are very easy to reuse and therefore useful to create more advanced UI tests. In this blogpost we are going to use Pages and Modules to test the contact form of the JDriven website. We will verify that a success message will appear if we submit a valid form. Pages have a url attribute which represent the address to the page. To get the complete url, Geb requires a baseUrl which we can define in the GebConfig.groovy

baseUrl = "http://www.jdriven.com/"

Continue reading →

Grails Goodness: Adding Health Check Indicators

Posted on by  
Hubert Klein Ikkink

With Grails 3 we also get Spring Boot Actuator. We can use Spring Boot Actuator to add some production-ready features for monitoring and managing our Grails application. One of the features is the addition of some endpoints with information about our application. By default we already have a /health endpoint when we start a Grails (3+) application. It gives back a JSON response with status UP. Let's expand this endpoint and add a disk space, database and url health check indicator.

We can set the application property endpoints.health.sensitive to false (securing these endpoints will be another blog post) and we automatically get a disk space health indicator. The default threshold is set to 10MB, so when the disk space is lower than 10MB the status is set to DOWN. The following snippet shows the change in the grails-app/conf/application.yml to set the property:

Continue reading →

Grails Goodness: Log Startup Info

Posted on by  
Hubert Klein Ikkink

We can let Grails log some extra information when the application starts. Like the process ID (PID) of the application and on which machine the application starts. And the time needed to start the application. The GrailsApp class has a property logStartupInfo which is true by default. If the property is true than some extra lines are logged at INFO and DEBUG level of the logger of our Application class.

So in order to see this information we must configure our logging in the logback.groovy file. Suppose our Application class is in the package mrhaki.grails.sample.Application then we add the following line to see the output of the startup logging on the console:

Continue reading →

Grails Goodness: Save Application PID in File

Posted on by  
Hubert Klein Ikkink

Since Grails 3 we can borrow a lot of the Spring Boot features in our applications. If we look in our Application.groovy file that is created when we create a new Grails application we see the class GrailsApp. This class extends SpringApplication so we can use all the methods and properties of SpringApplication in our Grails application. Spring Boot and Grails comes with the class ApplicationPidFileWriter in the package org.springframework.boot.actuate.system. This class saves the application PID (Process ID) in a file application.pid when the application starts.

In the following example Application.groovy we create an instance of ApplicationPidFileWriter and register it with the GrailsApp:

Continue reading →

Awesome Asciidoctor: Display Keyboard Shortcuts

Posted on by  
Hubert Klein Ikkink

When we want to explain in our documentation which keys a user must press to get to a function we can use the keyboard macro in Asciidoctor. The macro will output the key nicely formatted as a real key on the keyboard. The syntax of the macro is kbd:[key]. To get the desired output we must set the document attribute experimental otherwise the macro is not used.

In the next Asciidoctor example file we use the keyboard macro:

Continue reading →

Scala Snippet: How to filter a list in Scala

Posted on by  
Arthur Arts

In Scala, filtering and processing collections is easy and elegant. There are many filtermethods available, but the most used will probably the basic filter method. Here's a code example of some filtering on my (ex)camera collection. The filter method will not only work on Lists, but on any Scala collection.

object MyCameraCollection02 {

  case class Camera(brand: String, model: String, sensorType: String, yearBought: Int) {
    override def toString: String =
      s"$brand $model \t\t $sensorType \t($yearBought)"
  }

  def main(args: Array[String]) {
    val canon5dmarkIII = new Camera("Canon", "5D MkIII", "FF", 2013)
    val canon5dmarkII = new Camera("Canon", "5D MkII", "FF", 2009)
    val canon6d = new Camera("Canon", "6D", "FF", 2014)
    val canon550d = new Camera("Canon", "550D", "APS-C", 2010)
    val canon40d = new Camera("Canon", "40D", "APS-C", 2008)
    val canonIXUS330 = new Camera("Canon", "IXUS 330", "1/2.7", 2001)
    val canonIXUSZ90 = new Camera("Canon", "IXUS Z90", "APS-C", 1999)
    val panasonicGM1 = new Camera("Panasonic", "GM1", "M43", 2014)
    val panasonicFZ20 = new Camera("Panasonic", "FZ20", "1/2.5", 2005)
    val sonyrx100 = new Camera("Sony", "DSC-RX100", "1\"", 2013)
    val sonynex5 = new Camera("Sony", "NEX-5", "APS-C", 2011)
    val sonyr1 = new Camera("Sony", "DSC-R1", "APS-C", 2005)

    val myCameras = List(canon5dmarkIII, canon5dmarkII, canon6d, canon550d, canon40d, canonIXUS330, canonIXUSZ90, panasonicGM1, panasonicFZ20, sonyrx100, sonynex5, sonyr1)
    val canonCameras = myCameras filter (_.brand == "Canon") // Every Canon camera I ever owned
    val sonyCameras = myCameras filter (_.brand == "Sony") // Every Sony camera I ever owned
    val pansonicCameras = myCameras filter (_.brand == "Panasonic") // Every Panasonic camera I ever owned


    // apscCamera's only
    val apscCameras = myCameras filter (_.sensorType == "APS-C")
    println("==APS-C camera's owned==")
    apscCameras foreach println
    println()


    // Canon camera's which are not full frame. You can filter, filtered lists.
    val canonNonFF = myCameras filter (_.brand == "Canon") filter (_.sensorType != "FF")
    println("==Non-FF camera's owned==")
    canonNonFF foreach println
    println()

    // Filter by boolean expressions on class properties
    val apsBefore2012 = apscCameras filter (_.yearBought < 2012)
    println("==APS-C camera's bought before 2012 owned==")
    apsBefore2012 foreach println
    println()

    // Filter by combining boolean expressions.
    val ffcamerasBefore2012 = myCameras filter (cam => cam.yearBought < 2012 && cam.sensorType == "FF")
    println("==Every FF Camera I ever owned before 2012==")
    ffcamerasBefore2012 foreach println
    println()
  }
}

Continue reading →

shadow-left