Adding Tests

We will now add tests for the models and the views and a few functional tests in the tests package. Tests ensure that an application works, and that it continues to work when changes are made in the future.

Test harness

The project came bootstrapped with some tests and a basic harness. These are located in the tests package at the top-level of the project. It is a common practice to put tests into a tests package alongside the application package, especially as projects grow in size and complexity. A useful convention is for each module in the application to contain a corresponding module in the tests package. The test module would have the same name with the prefix test_.

The harness consists of the following setup:

  • pytest.ini - controls basic pytest configuration, including where to find the tests. We have configured pytest to search for tests in the application package and in the tests package.
  • .coveragerc - controls coverage config. In our setup, it works with the pytest-cov plugin that we use via the --cov options to the pytest command.
  • testing.ini - a mirror of development.ini and production.ini that contains settings used for executing the test suite. Most importantly, it contains the database connection information used by tests that require the database.
  • tests_require in setup.py - controls the dependencies installed when testing. When the list is changed, it is necessary to re-run $VENV/bin/pip install -e ".[testing]" to ensure the new dependencies are installed.
  • tests/conftest.py - the core fixtures available throughout our tests. The fixtures are explained in more detail in the following sections. Open tests/conftest.py and follow along.

Session-scoped test fixtures

  • app_settings - the settings dict parsed from the testing.ini file that would normally be passed by pserve into your app's main function.
  • app - the Pyramid WSGI application, implementing the pyramid.interfaces.IRouter interface. Most commonly this would be used for functional tests.

Per-test fixtures

  • tm - a transaction.TransactionManager object controlling a transaction lifecycle. Generally other fixtures would join to the tm fixture to control their lifecycle and ensure they are aborted at the end of the test.
  • testapp - a webtest.TestApp instance wrapping the app and is used to sending requests into the application and return full response objects that can be inspected. The testapp is able to mutate the request environ such that the tm fixture is injected and used by any code that touches request.tm. This should join the request.root ZODB model to the transaction manager as well, to enable rolling back changes to the database. The testapp maintains a cookiejar, so it can be used to share state across requests, as well as the transaction database connection.
  • app_request - a pyramid.request.Request object that can be used for more lightweight tests versus the full testapp. The app_request can be passed to view functions and other code that need a fully functional request object.
  • dummy_request - a pyramid.testing.DummyRequest object that is very lightweight. This is a great object to pass to view functions that have minimal side-effects as it will be fast and simple.

Unit tests

We can test individual APIs within our codebase to ensure they fulfill the expected contract that the rest of the application expects. For example, we will test the password hashing features we added to tutorial.security and the rest of our models.

Create tests/test_models.py such that it appears as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from tutorial import models

def test_page_model():
    instance = models.Page(data='some data')
    assert instance.data == 'some data'

def test_wiki_model():
    wiki = models.Wiki()
    assert wiki.__parent__ is None
    assert wiki.__name__ is None

def test_appmaker():
    root = {}
    models.appmaker(root)
    assert root['app_root']['FrontPage'].data == 'This is the front page'

def test_password_hashing():
    from tutorial.security import hash_password, check_password

    password = 'secretpassword'
    hashed_password = hash_password(password)
    assert check_password(hashed_password, password)
    assert not check_password(hashed_password, 'attackerpassword')
    assert not check_password(None, password)

Integration tests

We can directly execute the view code, bypassing Pyramid and testing just the code that we have written. These tests use dummy requests that we will prepare appropriately to set the conditions each view expects.

Update tests/test_views.py such that it appears as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
from pyramid import testing


class Test_view_wiki:
    def test_it_redirects_to_front_page(self):
        from tutorial.views.default import view_wiki
        context = testing.DummyResource()
        request = testing.DummyRequest()
        response = view_wiki(context, request)
        assert response.location == 'http://example.com/FrontPage'

class Test_view_page:
    def _callFUT(self, context, request):
        from tutorial.views.default import view_page
        return view_page(context, request)

    def test_it(self):
        wiki = testing.DummyResource()
        wiki['IDoExist'] = testing.DummyResource()
        context = testing.DummyResource(data='Hello CruelWorld IDoExist')
        context.__parent__ = wiki
        context.__name__ = 'thepage'
        request = testing.DummyRequest()
        info = self._callFUT(context, request)
        assert info['page'] == context
        assert info['page_text'] == (
            '<div class="document">\n'
            '<p>Hello <a href="http://example.com/add_page/CruelWorld">'
            'CruelWorld</a> '
            '<a href="http://example.com/IDoExist/">'
            'IDoExist</a>'
            '</p>\n</div>\n')
        assert info['edit_url'] == 'http://example.com/thepage/edit_page'


class Test_add_page:
    def _callFUT(self, context, request):
        from tutorial.views.default import add_page
        return add_page(context, request)

    def test_it_notsubmitted(self):
        context = testing.DummyResource()
        request = testing.DummyRequest()
        request.subpath = ['AnotherPage']
        info = self._callFUT(context, request)
        assert info['page'].data == ''
        assert info['save_url'] == request.resource_url(
            context, 'add_page', 'AnotherPage')

    def test_it_submitted(self):
        context = testing.DummyResource()
        request = testing.DummyRequest({
            'form.submitted': True,
            'body': 'Hello yo!',
        })
        request.subpath = ['AnotherPage']
        self._callFUT(context, request)
        page = context['AnotherPage']
        assert page.data == 'Hello yo!'
        assert page.__name__ == 'AnotherPage'
        assert page.__parent__ == context

class Test_edit_page:
    def _callFUT(self, context, request):
        from tutorial.views.default import edit_page
        return edit_page(context, request)

    def test_it_notsubmitted(self):
        context = testing.DummyResource()
        request = testing.DummyRequest()
        info = self._callFUT(context, request)
        assert info['page'] == context
        assert info['save_url'] == request.resource_url(context, 'edit_page')

    def test_it_submitted(self):
        context = testing.DummyResource()
        request = testing.DummyRequest({
            'form.submitted': True,
            'body': 'Hello yo!',
        })
        response = self._callFUT(context, request)
        assert response.location == 'http://example.com/'
        assert context.data == 'Hello yo!'

Functional tests

We will test the whole application, covering security aspects that are not tested in the unit and integration tests, like logging in, logging out, checking that the basic user cannot edit pages that it did not create, but that the editor user can, and so on.

Update tests/test_functional.py such that it appears as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
viewer_login = (
    '/login?login=viewer&password=viewer'
    '&came_from=FrontPage&form.submitted=Login'
)
viewer_wrong_login = (
    '/login?login=viewer&password=incorrect'
    '&came_from=FrontPage&form.submitted=Login'
)
editor_login = (
    '/login?login=editor&password=editor'
    '&came_from=FrontPage&form.submitted=Login'
)

def test_root(testapp):
    res = testapp.get('/', status=303)
    assert res.location == 'http://example.com/FrontPage'

def test_FrontPage(testapp):
    res = testapp.get('/FrontPage', status=200)
    assert b'FrontPage' in res.body

def test_missing_page(testapp):
    res = testapp.get('/SomePage', status=404)
    assert b'Not Found' in res.body

def test_referrer_is_login(testapp):
    res = testapp.get('/login', status=200)
    assert b'name="came_from" value="/"' in res.body

def test_successful_log_in(testapp):
    res = testapp.get(viewer_login, status=303)
    assert res.location == 'http://example.com/FrontPage'

def test_failed_log_in(testapp):
    res = testapp.get(viewer_wrong_login, status=400)
    assert b'login' in res.body

def test_logout_link_present_when_logged_in(testapp):
    res = testapp.get(viewer_login, status=303)
    res = testapp.get('/FrontPage', status=200)
    assert b'Logout' in res.body

def test_logout_link_not_present_after_logged_out(testapp):
    res = testapp.get(viewer_login, status=303)
    res = testapp.get('/FrontPage', status=200)
    res = testapp.get('/logout', status=303)
    assert b'Logout' not in res.body

def test_anonymous_user_cannot_edit(testapp):
    res = testapp.get('/FrontPage/edit_page', status=200)
    assert b'Login' in res.body

def test_anonymous_user_cannot_add(testapp):
    res = testapp.get('/add_page/NewPage', status=200)
    assert b'Login' in res.body

def test_viewer_user_cannot_edit(testapp):
    res = testapp.get(viewer_login, status=303)
    res = testapp.get('/FrontPage/edit_page', status=200)
    assert b'Login' in res.body

def test_viewer_user_cannot_add(testapp):
    res = testapp.get(viewer_login, status=303)
    res = testapp.get('/add_page/NewPage', status=200)
    assert b'Login' in res.body

def test_editors_member_user_can_edit(testapp):
    res = testapp.get(editor_login, status=303)
    res = testapp.get('/FrontPage/edit_page', status=200)
    assert b'Editing' in res.body

def test_editors_member_user_can_add(testapp):
    res = testapp.get(editor_login, status=303)
    res = testapp.get('/add_page/NewPage', status=200)
    assert b'Editing' in res.body

def test_editors_member_user_can_view(testapp):
    res = testapp.get(editor_login, status=303)
    res = testapp.get('/FrontPage', status=200)
    assert b'FrontPage' in res.body

Running the tests

We can run these tests by using pytest similarly to how we did in Run the tests. Courtesy of the cookiecutter, our testing dependencies have already been satisfied. pytest and coverage have already been configured. We can jump right to running tests.

On Unix:

$VENV/bin/pytest -q

On Windows:

%VENV%\Scripts\pytest -q

The expected result should look like the following:

.........................
25 passed in 3.87 seconds