Logo dévoreur 2 code

Tests and Code Quality - Tests, How Do They Work?

Written by Fabien SchlegelFabien Schlegel
published 9/1/20196 min

Tests, how do they work?

The follow-up to our first article. Today, we set off to discover the wonderful world of tests…

The TDD method

TDD, or Test Driven Development, is not a testing method but a way of writing code.

I mention it first simply because I’m not a fan.

As its name suggests, the principle of test-driven development is to start with the test. You write the test, it fails (well yes, the associated function doesn’t exist yet). Then you code the function and, hop, the test passes, you move on to the next one.

import unittest # the testing library

from words import capitalize # our function

class TestWords(unittest.TestCase):

    def test_capitalize(self):
        "Test that the first letter is uppercase"

        self.assertEqual(capitalize("bob"), "Bob")

if __name__ == '__main__':
    unittest.main()

In this Python example, we create a class that tests a function returning a word with its first letter capitalized. If we run this test:

fabien@T430:~/Projets/Sandbox$ python tests.py
Traceback (most recent call last):
  File "tests.py", line 3, in <module>
    from words import capitalize
ImportError: No module named 'words'

We get an import error, since the capitalize function doesn’t exist. So here it is:

def capitalize(word):
    return word.capitalize()

We run the test again and, magic, it works:

fabien@T430:~/Projets/Sandbox$ python tests.py
.
----------------------------------------------------------------------
Ran 1 test in 0.000s
OK

Where I’m not a fan of TDD is when you leave the land of unicorns and rainbows. On a real project, you end up writing more tests than code. And when you tackle a rewrite, you have to slog through the test and the code, or even several tests if you refactor, hack things apart with an axe, etc.

Indeed, it’s better to test only one situation per test. If our function contains several conditions, it may need several tests, which makes development more complex in the end.

Still, it’s handy in some situations, and it’s important to know this way of working.

Tests, nothing but tests

There are different types of tests, each suited to different situations. They have different purposes and different code coverage.

For Python, there are several testing libraries: unittest, which is built into the language, and pytest, a third-party library.

For Javascript, there are quite a few. For React, I use Jest and Enzyme.

Unit tests

Wikipedia definition

An example with Redux, to test an action.

// a simple action with one argument
export default (operande) => ({
  type: "ADD_OPERANDE",
  operande,
});
// Our awesome test
import { addOperande } from "..";

describe("Test addOperande Action", () => {
  it("add operande", () => {
    const operande = addOperande("+");
    expect(operande).toEqual({ type: "ADD_OPERANDE", operande: "+" });
  });
});

If we ever modify the action by adding an argument and run the test, it will fail.

With React and its component principle, unit testing is rather simple. Here I chose to group them by type with a __tests__ directory that holds, well, the tests.

When I use the Atomic Design method, I put each component in a directory and place the tests for that component right next to it.

If you want more unit tests and Python, go read these articles (in French)!

Integration tests

Wikipedia definition

As for me, I don’t write integration tests. With continuous integration tools, for web applications, I go straight from unit tests to end-to-end tests.

End-to-end tests

Here, no definition on Wikipedia. But the principle is to run tests in a real environment.

For big projects, there are testers who hunt down the application’s bugs and report them to the developers.

Indeed, these tests are based on the application’s user scenarios.

These tests are the only ones that truly check how software works in a real environment.

For the web, the best is Selenium.

Take Selenium, a web browser, the right driver to tie everything together, and we can test our application.

class TestSignIn(StaticLiveServerTestCase):

    def setUp(self):
        chrome_options = webdriver.ChromeOptions()
        chrome_options.add_argument('--no-sandbox')
        chrome_options.add_argument('--window-size=1420,1080')
        chrome_options.add_argument('--headless')
        self.driver = webdriver.Chrome(chrome_options=chrome_options)

        User.objects.create_user(username='johndoe', password='glass onion')

        self.driver.implicitly_wait(10)

    def tearDown(self):
        self.driver.quit()

    def _get_full_url(self, namespace):
        return self.live_server_url + reverse(namespace)

    def test_signin_succeed(self):
        """ test signin form succeed"""

        url = self._get_full_url('{}:login'.format(app_name))
        self.driver.get(url)
        self.driver.find_element_by_id('id_username').send_keys("johndoe")
        self.driver.find_element_by_id('id_password').send_keys("glass onion")
        self.driver.find_element_by_id('signInForm').submit()
        self.driver.implicitly_wait(10)
        self.assertTrue(self.driver.find_elements_by_id('linkToProfile'))

In this Django example, a quick breakdown…

  • setUp configures Chrome: here we drop the sandbox mode, choose the window size, and the browser runs without a screen (handy in a Docker environment).
  • tearDown turns off the lights at the end of the test.
  • _get_full_url retrieves the called URL from its namespace.
  • test_signin_succeed, the heart of the matter, is our test:
    • We tell Selenium which form to fill in with the associated info
    • It submits it, waits a bit for the page to load
    • It checks that an id exists in the page. If it is present, the user sees the link to their profile and everything is ok.

And what about mocks

Mocks are both magical and a total pain. They let us imitate (thanks Google Translate) what we can’t have available for our tests.

The magic is, for example, when my site depends on some API. I can’t send requests to that API during my tests, so how do we proceed? Well, we mock! We write a function that returns the expected response to our API request.

With JS frameworks, React for instance, we use localstorage, which is a feature built into the browser.

During our tests, we don’t necessarily have access to it, so we use this:

const mock = (() => {
  let store = {};
  return {
    getItem(key) {
      return store[key];
    },
    setItem(key, value) {
      store[key] = value.toString();
    },
    clear() {
      store = {};
    },
    removeItem(key) {
      delete store[key];
    },
  };
})();

export default Object.defineProperty(window, "localStorage", { value: mock });

And hop! We have the localstorage functions available for our tests.

I can feel the question coming: why did you say mocks are a pain? They’re actually awesome!

Yes, but no, because in practice you can be tempted to mock anything and everything. That’s not the goal of tests. The goal is to check the robustness of our project in conditions as close to reality as possible.

A mock is a simulation that should only be used when you have no choice, not out of convenience.

A short conclusion

Here we saw that tests bring a huge amount to our projects.

They guarantee non-regression and keep an eye on how our code works.

Tests aren’t magic either: if nobody runs them, we can change everything and nobody will be any the wiser.

On the other hand, if tests are automated on every merge request, or better, on every commit, we can monitor how the code evolves. Merge requests will be easier for the team to review.


Share the post

Table of contents