Pyramid : Création de tests fonctionnels



Les tests garantissent que l application fonctionne et qu elle continue de fonctionner lorsque des modifications seront apportées à l avenir.

.

Tests unitaires, tests d intégration et tests fonctionnels

.

Add required packages

Insert the following code immediately following the requires block in the file myproject/setup.py.:

requires = [
  "plaster_pastedeploy",
  "pyramid ,
  ...
  "pyramid_debugtoolbar",
  "waitress",
]

tests_require = [
  "WebTest >= 1.3.1",  # py3 compat
  "pytest",
  "pytest-cov",
]

Remember to change the dependency.:

zip_safe=False,
  extras_require={
      "testing": tests_require,
  },
  install_requires=requires,

As always, whenever you change your dependencies, make sure to run the correct pip install -e command.:

$VENV/bin/pip install -e \".[testing]\"

.

Création d un dossier tests

Commencez par supprimer tests.py, puis créez un nouveau répertoire pour contenir nos nouveaux tests ainsi qu un nouveau fichier vide tests / \\ init\\.py.

.

Tester les views

Nous allons créer un nouveau fichier tests/test\_views.py, en ajoutant une classe BaseTest utilisée comme base pour les autres classes de test. Ensuite, nous ajouterons des tests pour chaque fonction d affichage que nous avons précédemment ajoutée à notre application.

Nous allons ajouter deux classes de test: UsersListTests, UserEditTests. Ils testent les vues users\_list et user\_edit.

Créez un tutoriel /tests/test\_views.py tel qu il apparaisse comme suit: ::

import unittest import transaction

from pyramid import testing

def dummy_request(dbsession): return testing.DummyRequest(dbsession=dbsession)

class BaseTest(unittest.TestCase): def setUp(self): from ..models import get_tm_session self.config = testing.setUp(settings={ sqlalchemy.url": "mysql://root:phuoc@localhost/bd_mesavoirs?charset=utf8" }) self.config.include("..models") self.config.include("..routes")

    session_factory = self.config.registry["dbsession_factory"]
    self.session = get_tm_session(session_factory, transaction.manager)

    self.init_database()

def init_database(self):
    from ..models.meta import Base
    session_factory = self.config.registry["dbsession_factory"]
    engine = session_factory.kw["bind ]
    Base.metadata.create_all(engine)

def tearDown(self):
    testing.tearDown()
    transaction.abort()

def makeUser(self, name, role, password="dummy"):
    from ..models import User
    user = User(name=name, role=role)
    user.set_password(password)
    return user

def makePage(self, name, data, creator):
    from ..models import Page
    return Page(name=name, data=data, creator=creator)

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

def test_it(self):
    from ..routes import PageResource

    # add a page to the db
    user = self.makeUser("foo",  editor")
    page = self.makePage( iDoExist", "Hello CruelWorld IDoExist", user)
    self.session.add_all([page, user])

    # create a request asking for the page we ve created
    request = dummy_request(self.session)
    request.context = PageResource(page)

    # call the view we re testing and check its behavior
    info = self._callFUT(request)
    self.assertEqual(info["page"], page)
    self.assertEqual(
        info["content"],
        "<div class=\"document\">\

" "

Hello " "CruelWorld " "" iDoExist" "

\
\ ") self.assertEqual(info[ edit_url"], "http://example.com/IDoExist/edit_page")

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

def makeContext(self, page):
    from ..routes import PageResource
    return PageResource(page)

def test_it_notsubmitted(self):
    user = self.makeUser("foo",  editor")
    page = self.makePage( abc", "hello", user)
    self.session.add_all([page, user])

    request = dummy_request(self.session)
    request.context = self.makeContext(page)
    info = self._callFUT(request)
    self.assertEqual(info["pagename"],  abc")
    self.assertEqual(info[ save_url"],
                     "http://example.com/abc/edit_page")

def test_it_submitted(self):
    user = self.makeUser("foo",  editor")
    page = self.makePage( abc", "hello", user)
    self.session.add_all([page, user])

    request = testing.DummyRequest({"form.submitted : True,
                                    "body": "Hello yo!"},
                                   dbsession=self.session)
    request.context = self.makeContext(page)
    response = self._callFUT(request)
    self.assertEqual(response.location, "http://example.com/abc")
    self.assertEqual(page.data, "Hello yo!")

When this test is run, each test method creates a \"real\" WSGI application using the main function in your myproject.init module, using WebTest to wrap that WSGI application. It assigns the result to self.testapp. In the test named test_root, the TestApp s GET method is used to invoke the root URL. Finally, an assertion is made that the returned HTML contains the text Pyramid.

See the WebTest documentation for further information about the methods available to a webtest.app.TestApp instance.


Publié le : 06-02-2018 - 18:00