We’re Hiring! Front End Lead Based in Stockholm

We are looking for a front end expert to take on the role of lead front end developer for the loadimpact.com site and application, being a part of our upcoming redesign of the whole site, service and user flow.

What is loadimpact.com then?

Load Impact is the world’s most widely used online load testing service, with over 100,000 users from 190+ countries and over a million executed load tests – Google “web load test”!

The company is small but very experienced in developing applications for performance testing and monitoring. We started out as a software development consulting company way back in 2000, developing performance test and measurement software for customers such as Nasdaq and the European space agency. We wrote both hardcore, low-level networking software and high-level web user interfaces and became quite good at both of those things. We pride ourselves on understanding the lower levels of a networked application while at the same time realizing how incredibly important UX is. In 2009 we took the step and launched loadimpact.com, becoming a product company rather than a consulting company, and we have never looked back.

We are located in Stockholm, Sweden and San Francisco, USA. This job opening is in Stockholm.

This is a chance to get the best of both worlds – you get to build something practically from scratch and decide how to do things while at the same time you’re supported by a successful, global business with a very strong user base and sound financial backing. You will be part of a small and very competent dev team, using the latest and greatest technologies and working in a modern and agile environment.

Being part of a small team means you get a lot of say in what happens in general, and can influence your own work situation. As a company, we are very “flat” (no hierarchies) and that means you’ll have a say in most decisions we make as a company, if you want to.

You need to be really, really good at:

HTML, CSS & Javascript

You need to be be knowledgeable about:

Usability / UI design
Common JS libraries/frameworks
Browser support/portability/quirks
Common data formats: JSON, XML
Responsive design

You should have some knowledge or experience of:

Client-side optimization (minification, sprites, lazy-loading etc)
Git / Github
SEO basics (the common-sense stuff, no black hat tricks thank you)
Common web servers: Apache, Nginx
Web analytics & growth hacking
SQL
Cloud operations (e.g. using Amazon EC2 and/or other AWS services)
Web application protocols: HTTP, HTTPS

The office is located in Stockholm, Sweden. A very scenic city, with excellent infrastructure, clean streets, low crime, many bars, fantastic coffee. A bit cool in winter, but who cares, we just buy more coffee. There is also a very vibrant tech startup scene in Stockholm, much thanks to companies like Spotify, Skype, King.com (Candy crush), Mojang (Minecraft) and others that started and are still operating here. The city is attracting more and more world-class IT entrepreneurs and developers – it is a very dynamic environment to work in, with a lot of industry colleagues to hang out with and learn from. Our office is very centrally located, by the way, with a fantastic view of the city harbour 🙂

 

photo

Actual view from our desks!

How to apply:

Email your resume and info to ragnar@loadimpact.com.

We look froward to hearing from you!

Deadline July 1, 2014.

Test Driven Development and CI using JavaScript [Part II]

This is the second half of a two part article on Test Driven Development and Continuous Integration (CI) using JavaScript. Part I covers different types of testing and approaches to Test Driven Development (TDD).

Behavior-Driven Development (BDD) is a specialized version of Test Driven Development (TDD) focused on behavioral specifications. Since TDD does not specify how the test cases should be done and what needs to be tested, BDD was created in response to these issues.

It’s easy to talk about Behavioral Driven Development (BDD), but it’s more difficult to actually put it into practice. BDD is a fairly new concept, so it’s not completely intuitive for some coders who have been working with Continuous Integration (CI) for a long time.

This article gives a real-world example application using the concept of a “Shapes” object. The “Shapes” object contains classes for each shape and the application is a small JavaScript application that uses BDD for testing.

BDD and Software Testing

This tutorial covers how to use BDD to test your JavaScript code. In the following example, some test cases are written along with the corresponding code. The code is then refactored to fix bug issues.

Project: Create an application that contains a set of shapes. For every shape, calculate its area.

Application structure

You can create different kinds of folder structures for your applications. For example, you can divide your code into public and private folders to correspond to your class types.

Create a structure for your project using the following:

+ public 
   + javascripts 
       + app               
       + lib 
           - require.js 
+ private 
   + javascripts 
       + lib 
           + jasmine-2.0.0 
.	... 
       + spec 
- SpecRunner.html 

Save your Jasmine libraries in the private folder. In the public folder, store RequireJS to use in your models.

Creating a test

Using TDD as methodology, you start creating small test cases. Test cases require good design, but you also need to consider your code. You can also rewrite some of your test cases as you improve your code.

Start creating tests for your application. For example, the following is a list of considerations you could make about your application:

  • Do you want to organize my shapes into classes? Since a shape could represent one object, it’s a good idea to design a class for each shape.

  • You will probably need a method to calculate the area of your shapes. 

The following is a test case that fits the above two code requirements:

describe("Shapes", function () {
    describe("Square", function () {
        var that = this;

        beforeEach(function (done) {
            require(['Shape/Square'], function (Square) {
                that.shape = new Square();
                done();
            });
        });

        it("with side 0 should have an area of 0", function () {
            expect(that.shape.getArea(0)).toBe(0);
        });

        it("with side 2 should have an area of 4", function () {
            expect(that.shape.getArea(2)).toBe(4);
        });

        it("with side 4 should have an area of 16", function () {
            expect(that.shape.getArea(4)).toBe(16);
        });

        it("with side 123.123 should have an area of 15159.27", function () {
            expect(that.shape.getArea(123.123)).toBe(Math.pow(123.123, 2));
        });
    });
});

/private/javascripts/spec/Shape/SquareSpec.js

The above test case fits the division specifications.

  • Suites: The method describe is used with the story’s name. In this case, you want to describe the actions to apply to Shapes and Square. The second argument is a function, which will contain Spec or more Suites. 
  • Spects: The keyword it is used with a “with XXX should” sentence. The way the sentence is written varies with the test case, but you should always write it as if you are writing a user story.  The second argument is a function where you start using your code for testing.
  • Expect: This statement helps you test code with simple sentences for output.  These statements usually do comparisons between values. They start with expect and find different kinds of “Matches,” which are comparison functions. An example of a “Match” is the function toBe .

This code gives you tips for organizing the code later.  The story for the first test looks like this:

  • Given a Shape which is a Square
  • And with side 0
  • Then the shape should have an area of 0

In order to create this story and obtain the right result, you create expectations: 

  • expect the area of 0 toBe 0

As you can see, it is very easy to read the tests, which allows you to create stories.

Creating the model

Now that we did a small test, we may have some idea about how to organize our code. We will create a base class called Shape.js and a class that represents the shape Square.

define("Shape/Shape", [], function() {
    function Shape() {
    }

    Shape.prototype.getArea = function() {
        return 0;
    };

    return Shape;
});
/public/javascripts/app/Shape/Shape.js
define("Shape/Square", ["Shape/Shape"], function (Shape) {
    function Square() {
        Shape.call(this);
    }
    Square.prototype = new Shape();
    Square.prototype.constructor = Square;

    Square.prototype.getArea = function (side) {
        return side * side;
    };

    return Square;
});

/public/javascripts/app/Shape/Square.js

As you can see, our shape contains a method to calculate the area. In the case of the Square, we need to pass it an argument for the side.

Running tests

A SpecRunner file is a file that runs all your test cases. You can organize them into suites and sets of SpecRunners. For this example, you create one file that runs all test cases.

Open the file SpecRunner.html and modify it with the following content:

<!DOCTYPE HTML>

<html>

<head>
  <metahttp-equiv="Content-Type"content="text/html; charset=UTF-8">
  <title>Jasmine Spec Runner v2.0.0</title>

  <link rel="shortcut icon"type="image/png"
href="private/javascripts/lib/jasmine-2.0.0/jasmine_favicon.png">
  <link rel="stylesheet"type="text/css"
href="private/javascripts/lib/jasmine-2.0.0/jasmine.css">

  <script type="text/javascript"
src="public/javascripts/lib/require.js"></script>
  <script type="text/javascript">
  requirejs.config({
  baseUrl: 'public/javascripts/app',
  paths: {
     jasmine: 'private/javascripts/lib/jasmine-2.0.0/jasmine'
  },
  shim: {
     jasmine: {
        exports: 'jasmine'
     }
  }
});
</script>

    <script type="text/javascript" 
src="private/javascripts/lib/jasmine-2.0.0/jasmine.js"></script>
    <script type="text/javascript" 
src="private/javascripts/lib/jasmine-2.0.0/jasmine-html.js"></script>
    <script type="text/javascript" 
src="private/javascripts/lib/jasmine-2.0.0/boot.js"></script>

    <!-- include source files here... -->
    <script type="text/javascript" 
src="public/javascripts/app/Shape/Square.js"></script>

    <!-- include spec files here... -->
    <script type="text/javascript" 
src="private/javascripts/spec/Shape/SquareSpec.js"></script>

</head>

<body>
</body>

</html>

/SpecRunner.html

The content is divided in three main sections:

  • Load and configure libraries for requireJS (public/javascripts/lib/require.js).
  • Load the necessary libraries for Jasmine (private/javascripts/lib/jasmine/…).
  • Load the application source files (public/javascripts/app/Shape/Square.js).
  • Load the test source files (private/javascripts/spec/Shape/SquareSpec.js)

If you execute (open) the file with your favorite browser, you see the following result:

Green Lines copy

All green labels show us that all tests have been passed correctly.

Refactoring code

In most cases, you’ll need to do a least a little refactoring after running your test cases. The following is an example of some real-world questions you could have about the test case results:

  • You could set the size of “side” using the method setSide instead of passing it though getArea method.

Do the following changes to the test cases, which create a new method setSide

describe("Shapes", function () {
   describe("Square", function () {
      var that = this;

      beforeEach(function (done) { 
            require(['Shape/Square'], function (Square) { 
              that.shape = new Square(); 
              done(); 
            }); 
      });

      it("with side 0 should have an area of 0", function () { 
         that.shape.setSide(0); 
         expect(that.shape.getArea()).toBe(0); 
      });

      it("with side 2 should have an area of 4", function () { 
         that.shape.setSide(2); 
         expect(that.shape.getArea()).toBe(4); 
      });

      it("with side 4 should have an area of 16", function () { 
         that.shape.setSide(4); 
         expect(that.shape.getArea()).toBe(16);
      });

      it("with side 123.123 should have an area of 15159.27", function () { 
         that.shape.setSide(123.123); 
         expect(that.shape.getArea()).toBe(Math.pow(123.123, 2)); 
    }); 
  }); 
});

/private/javascripts/spec/Shape/SquareSpec.js

After you make the changes to the test cases, refresh your browser. In this example, the test cases fail.

fail copy

Since the test cases failed, you know you’ve broken your application. The failed test cases are the advantage of BDD since these test cases let you know that there are errors in your application – before you write too much code . Because you’ve only written a small amount of code, you only have a small amount of code to refactor from the failed test cases. If you had written the entire application, you would have hours of refactoring ahead of you. Even if you have one class used in several modules, every module has its own test.

Now we can fix the model:

define("Shape/Square", ["Shape/Shape"], function (Shape) {    
    function Square() {
        Shape.call(this);

        this.side = 0;
    }
    Square.prototype = new Shape();
    Square.prototype.constructor = Square;

    Square.prototype.setSide = function (value) {
        this.side = value;
    };

    Square.prototype.getArea = function () {
        return this.side * this.side;
    };

    return Square;
});

/public/javascripts/app/Shape/Square.js

After you refactor your code, the tests will now run successfully.

In this tutorial, a basic use for TDD in JavaScript was used. However, you can use TDD in any language that supports test cases.

————

 

avatarThis post was written by Miguel Dominguez. Miguel is currently Senior Software Developer at digitallabs AB but also works as a freelance developer. His focus is on mobile application (android) development, web front-end development (JavaScript, CSS, HTML5) and back-end (mvc, .net, java). Follow Miguel’s blog.

Test Driven Development and CI using JavaScript [Part I]

In this tutorial, we will learn how to apply TDD (Test-Driven Development) using JavaScript code. This is the first part of a set of tutorials that includes TDD and CI (Continuous Integration) using JavaScript as the main language.

Some types of testing

There are several approaches for testing code and each come with their own set of challenges. Emily Bache, author of The Coding Dojo Handbook, writes about them in more detail on her blog – “Coding is like cooking

1. Test Last: in this approach, you code a solution and subsequently create the test cases.

  • Problem 1: It’s difficult to create test cases after the code is completed.
  • Problem 2: If test cases find an issue, it’s difficult to refactor the completed code.

2. Test First: you design test cases and then write the code.

  • Problem 1: You need a good design and formulating test cases increases the design stage, which takes too much time.
  • Problem 2: Design issues are caught too late in the coding process, which makes refactoring the code more difficult due to specification changes in the design. This issue also leads to scope creep.

TDD-diagram-1

3. Test-Driven: You write test cases parallel to new coding modules. In other words, you add a task for unit tests as your developers are assigned different coding tasks during the project development stage.

TDD-diagram-2

 

TDD approach

TDD focuses on writing code at the same time as you write the tests. You write small modules of code, and then write your tests shortly after.

Patterns to apply to the code:

  • Avoid direct calls over the network or to the database. Use interfaces or abstract classes instead.
  • Implement a real class that implements the network or database call and a class which simulates the calls and returns quick values (Fakes and Mocks).
  • Create a constructor that uses Fakes or Mocks as a parameter in its interface or abstract class.

Patterns to apply to unit tests: 

  • Use the setup function to initialize the testing, which initializes common behavior for the rest of the unit test cases.
  • Use the TearDown function to release resources after a unit test case has finalized.
  • Use “assert()” to verify the correct behavior and results of the code during the unit test cases.
  • Avoid dependency between unit test cases.
  • Test small pieces of code.

 

Behavior-Driven Development

Behavior-Driven Development (BDD) is a specialized version of TDD focused on behavioral specifications. Since TDD does not specify how the test cases should be done and what needs to be tested, BDD was created in response to these issues.

Test cases are written based on user stories or scenarios. Stories are established during the design phase. Business analysts, managers and project/product managers gather the design specifications, and then users explain the logical functionality for each control. Specifications also include a design flow so test cases can validate proper flow.

This is an example of the language used to create a BDD test story:

Story: Returns go to stock

In order to keep track of stock

As a store owner

I want to add items back to stock when they’re returned


Scenario 1Refunded items should be returned to stock

Given a customer previously bought a black sweater from me

And I currently have three black sweaters left in stock

When he returns the sweater for a refund

Then I should have four black sweaters in stock


Scenario 2:  Replaced items should be returned to stock

Given that a customer buys a blue garment

And I have two blue garments in stock

And three black garments in stock.

When he returns the garment for a replacement in black,

Then I should have three blue garments in stock

And two black garments in stock

 

Frameworks to Install

1. Jamine

Jasmine  is a set of standalone libraries that allow you to test JavaScript based on BDD. These libraries do not require DOM, which make them perfect to test on the client side and the server side. You can download it from http://github.com/pivotal/jasmine

It is divided into suites, specs and expectations

.Suites define the unit’s story. 

.Specs define the scenarios. 

.Expectations define desired behaviors and results. 

Jasmine has a set of helper libraries that lets you organize tests.  

2. RequreJS

RequireJS is a Javascript library that allows you to organize code into modules, which load dynamically on demand.

By dividing code into modules, you can speed up the load-time for application components and have better organization of your code.

You can download RequireJS from http://www.requirejs.org

Part II of this two part tutorial will discuss Behavioral Driven Testing and Software Testing – how to use BDD to test your JavaScipt code. Don’t miss out, subscribe to our blog below. 

————-

avatar

This post was written by Miguel Dominguez. Miguel is currently Senior Software Developer at digitallabs AB but also works as a freelance developer. His focus is on mobile application (android) development, web front-end development (javascript, css, html5) and back-end (mvc, .net, java). Follow Miguel’s blog.

Node.js vs PHP – using Load Impact to visualize node.js efficiency

It could be said that Node.js is the new darling of web server technology. LinkedIn have had very good results with it and there are places on the Internet that will tell you it can cure cancer.

In the mean time, the old work horse language of the Internet, PHP, gets a steady stream of criticism. and among the 14k Google hits for “PHP sucks” (exact term), people will say the most funny terrible things about the language while some of the critique is actually quite well balanced. Node.js introduces at least two new things (for a broader audience). First, the ability to write server side JavaScript code. In theory this could be an advantage since JavaScript is more important than ever on the client side and using the same language on server and browser would have many benefits. That’s at least quite cool.

The other thing that makes Node.js different is that it’s completely asynchronous and event driven. Node is based on the realization that a lot of computer code actually just sits idle and wait for I/O most of the time, like waiting for a file to be written to disk or for a MySQL query to return data. To accomplish that, more or less every single function in Node.js is non-blocking.

When you ask for node to open a file, you don’t wait for it to return. Instead, you tell node what function to pass the results to and get on with executing other statements. This leads to a dramatically different way to structure your code with deeply nested callbacks and anonymous function and closures. You end up with something  like this:

doSomething(val, function(err,result){
  doSomethingElse(result,function(err,res){
    doAbra();
    doKadabra(err, res, function() {
      ...
      ...
    });
  });
});

It’s quite easy to end up with very deep nesting that in my opinion sometimes affects code readability in a negative way. But compared to what gets said about PHP, that’s very mild critique. And.. oh! The third thing that is quite different is that in Node.js, you don’t have to use a separate http(s) server. It’s quite common to put Node.js behind a Nginx, but that’s not strictly needed. So the heart of a typical Node.js web application is the implementation of the actual web server.

A fair way to compare

So no, it’s not fair to say that we compare Node.js and PHP. What we really compare is Node.js and PHP+Apache2 (or any other http server). For this article, I’ve used Apache2 and mod_php since it’s by far the most common configuration. Some might say that I’d get much better results if I had used Nginx or Lighthttpd as the http server for PHP. That’s most likely very true, but at the end of the day, server side PHP depends on running in multiple separate processes. Regardless if we create those processes with mod_php or fastcgi or any other mechanism. So, I’m sticking with the standard server setup for PHP and I think that makes good sense.

The testing environment

So we’re pitting PHP+Apache2 against a Node.js based application. To keep things reasonable, I’ve created a very (really, very) simple application in both PHP5 and Node.js. The application will get 50 rows of data from a WordPress installation and output it as a json string. That’s it, nothing more. The benefit of keeping it this simple was (a) that I didn’t have to bother about too many implementation details between the two languages and (b) more important that we’re not testing my ability to code, we’re really testing the difference in architecture between the two. The server we’re  using for this test is a virtual server with:

  • 1 x Core Intel(R) Xeon(R) CPU E5-2670 0 @ 2.60GHz
  • 2 Gb RAM.
  • OS is 64 Bit Ubuntu 12.10 installed fresh before running these tests.
  • We installed the Load Impact Server metric agent.

For the tests, we’re using:

  • Apache/2.2.22 and
  • PHP 5.4.6.
  • Node.js version 0.8.18 (built using this script)
  • MySQL is version 5.5.29.
  • The data table in the tests is the options table from a random WordPress blog.
The scripts we’re using:

Node.js (javascript):

// Include http module,
var http = require('http'),
mysql = require("mysql");

// Create the connection.
// Data is default to new mysql installation and should be changed according to your configuration.
var connection = mysql.createConnection({
   user: "wp",
   password: "****",
   database: "random"
});

// Create the http server.
http.createServer(function (request, response) {
   // Attach listener on end event.
   request.on('end', function () {

      // Query the database.
      connection.query('SELECT * FROM wp_options limit 50;', function (error, rows, fields) {
         response.writeHead(200, {
            'Content-Type': 'text/html'
         });
         // Send data as JSON string.
         // Rows variable holds the result of the query.
         response.end(JSON.stringify(rows));
      });
   });
// Listen on the 8080 port.
}).listen(8080);

PHP code:

<!--?php $db = new PDO('mysql:host=localhost;dbname=*****',     'wp',     '*****'); $all= $db--->query('SELECT * FROM wp_options limit 50;')->fetchAll();
echo json_encode($all);

The PHP script is obviously much shorter, but on the other hand it doesn’t have to implement a full http server either.

Running the tests

The Load Impact test configurations are also very simple, these two scripts are after all typical one trick ponies, so there’s not that much of bells and whistles to use here. To be honest, I was surprised how many concurrent users I had to use in order to bring the difference out into the light. The test scripts had the following parameters:

  • The ramp up went from 0-500 users in 5 minutes
  • 100% of the traffic comes from one source (Ashburn US)
  • Server metrics agent enabled
The graphics:
On the below images. the lines have the following meanings:
  • Green line: Concurrent users
  • Blue line: Response time
  • Red line: Server CPU usage

Node.js up to 500 users.

The first graph here shows what happens when we load test the Node.js server. The response time (blue) is pretty much constant all through the test. My back of a napkin analysis of the initial outliers is that they have to do with a cold MySQL cache. Now, have a look at the results from the PHP test:

Quite different results. It’s not easy to see on this screen shot, but the blue lines is initially stable at 320 ms response time up to about 340 active concurrent users. After that, we first see a small increase in response time but after additional active concurrent users are added, the response time eventually goes through the roof completely.

So what’s wrong with PHP/Apache?

Ok, so what we’re looking at is not very surprising, it’s the difference in architecture between the two solutions. Let’s think about what goes on in each case.

When Apache2 serves up the PHP page it leaves the PHP execution to a specific child process. That child process can only handle one PHP request at a time so if there are more requests than than, the others have to wait. On this server, there’s a maximum of 256 clients (MaxClients) configured vs 150 that comes standard. Even if it’s possible to increase MaxClients to well beyond 256, that will in turn give you a problem with internal memory (RAM). At the end, you need to find the correct balance between max nr of concurrent requests and available server resources.

But for Node, it’s easier. First of all, in the calm territory, each request is about 30% faster than for PHP, so in pure performance in this extremely basic setup, Node is quicker. Also going for Node is the fact that everything is in one single process on the server. One process with one active request handling thread. So thre’s no inter process communication between different instances and the ‘mother’ process. Also, per request, Node is much more memory efficient. PHP/Apache needs to have a lot of php and process overhead per concurrent worker/client while Node will share most of it’s memory between the requests.

Also note that in both these tests, CPU load was never a problem. Even if CPU loads varies with concurrent users in both tests it stays below 5% (and yes, I did not just rely on the graph, I checked it on the server as well). (I’ll write a follow up on this article at some point when I can include server memory usage as well). So we haven’t loaded this server into oblivion in any way, we’ve just loaded it hard enough for the PHP/Aapache architecture to start showing some of it’s problems.

So if Node.js is so good…

Well of course. There are challenges with Node, both technical and cultural. On the technical side, the core design idea in Node is to have one process with one thread makes it a bit of a challenge to scale up on a multi core server. You may have already noted that the test machine uses only one core which is an unfair advantage to Node. If it had 2 cores, PHP/Apache would have been able to use that, but for Node to do the same, you have to do some tricks.

On the cultural side, PHP is still “everywhere” and Node is not. So if you decide to go with Node, you need to prepare to do a lot more work yourself, there’s simply nowhere near as many coders, web hotels, computer book authors, world leading CMS’es and what have you. With PHP, you never walk alone.

Conclusion

Hopefully, this shows the inherit differences in two different server technologies. One old trusted and one young and trending. Hopefully it’s apparent that your core technical choices will affect your server performance and in the end, how much load you can take. Designing for high load and high scalability begins early in the process, before the first line of code is ever written.

And sure, in real life, there are numerous of tricks available to reduce the effects seen here. In real life, lots of Facebook still runs on PHP.

About Load Impact

Load Impact is the leading cloud-based load testing software trusted by over 123,000 website, mobile app and API developers worldwide.

Companies like JWT, NASDAQ, The European Space Agency and ServiceNow have used Load Impact to detect, predict, and analyze performance problems.
 
Load Impact requires no download or installation, is completely free to try, and users can start a test with just one click.
 
Test your website, app or API at loadimpact.com

Enter your email address to follow this blog and receive notifications of new posts by email.