HTTP Tests
To make a request in your tests, you may use the get, post, put, patch, or delete methods within your test. These methods do not actually issue a "real" HTTP request to your application. Instead of returning a Masonit class Response instance, test request methods return a HTTPTestResponseinstance, which provides a variety of helpful assertions that allow you to inspect and assert application's responses.
1
def test_basic_request(self):
2
self.get("/").assertOk()
Copied!

Getting request and response

The request and responses of a test can be fetch by accessing the request and response attributes.
1
def test_request_and_response(self):
2
request = self.get('/testing').request # <masonite.requests.Request>
3
response = self.get('/testing').response # <masonite.response.Response>
Copied!

Registering routes

During tests you can register routes used only for testing purposes. For this you can use the addRoutes() method at beginning of your tests:
1
@classmethod
2
def setUpClass(cls):
3
super().setUpClass()
4
cls.addRoutes(
5
Route.get("/", "[email protected]"),
6
Route.post("/", "[email protected]"),
7
)
Copied!

Checking if a route exists

To check if a route exists, we can simple use either get or post:
1
def test_route_exists(self):
2
self.assertTrue(self.get('/testing'))
3
self.assertTrue(self.post('/testing'))
Copied!

Request Headers

You may use the withHeaders() method to customize the request's headers before it is sent to the application. This method allows you to add any headers you would like to the request by providing them as a dict:
1
request = self.withHeaders({"X-TEST": "value"}).get("/").request
2
self.assertEqual(request.header("X-Test"), "value")
Copied!

Cookies

You may use the withCookies() method to set cookie values before making a request. This method accepts a dictionary of name / value pairs:
1
self.withCookies({"test": "value"}).get("/").assertCookie("test", "value")
Copied!

Authentication

If you want to make authenticated requests in your tests, you can use the actingAs() method that takes a given User record and authenticate him during the request.
1
user = User.find(1)
2
self.actingAs(user).get("/")
Copied!

CSRF Protection

By default, all calls to your routes with the above methods will be without CSRF protection. The testing code will allow you to bypass that protection.
This is very useful since you don't need to worry about setting CSRF tokens on every request but you may want to enable this protection. You can do so by calling the withCsrf() method on your test.
1
def test_csrf(self):
2
self.withCsrf()
3
self.post("/unit/test/json", {"test": "testing"})
Copied!
This will enable it on a specific test but you may want to enable it on all your tests. You can do this by adding the method to your setUp() method:
1
def setUp(self):
2
super().setUp()
3
self.withCsrf()
Copied!
Again you can disable this behaviour with withoutCsrf() method.

Exceptions handling

As you have noticed, Masonite has exception handling which it uses to display useful information during development.
This is an issue during testing because we wan't to be able to see more useful testing related issues. Because of this, testing will disable Masonite's default exceptions handling and you will see more useful exceptions during testing. If you want to use Masonite's built in exceptions handling then you can enable it by running:
1
def setUp(self):
2
super().setUp()
3
self.withExceptionHandling()
Copied!
You can also disable exceptions handling again by using:
1
def test_something(self):
2
self.withExceptionHandling()
3
self.get("/").assertUnauthorized()
4
self.withoutExceptionHandling()
5
self.get("/")
Copied!

Available Assertions

Masonite provides a variety of assertions methods to inspect and verify request/response logic when testing your application. Those assertions are available on the HTTPTestResponse returned by get, post, put, patch, or delete.

assertContains

Assert that returned response contains the given content string. Note that the response content will be eventually decoded if required.
1
self.get("/").assertContains(content)
Copied!

assertNotContains

Assert that returned response does not contain the given content string. Note that the response content will be eventually decoded if required.
1
self.get("/").assertNotContains(content)
Copied!

assertContainsInOrder

Assert that returned response contains in order the given strings. Note that the response content will be eventually decoded if required.
1
self.get("/").assertContains(string1, string2, ...)
Copied!

assertNoContent

Assert that returned response has no content and the given HTTP status code. The default status code that is asserted is 204.
1
self.get("/").assertNoContent(status=204)
Copied!

assertIsNamed

Assert that given route has the given name.
1
self.get("/").assertIsNamed("home")
Copied!

assertIsNotNamed

Assert that given route has not the given name.
1
self.get("/").assertIsNotNamed("admin")
Copied!

assertIsStatus

Assert that the response has the given HTTP status code:
1
self.get("/").assertIsStatus(201)
Copied!

assertOk

Assert that the response returns a 200 status code:
1
self.get("/").assertOk()
Copied!

assertCreated

Assert that the response returns a 201 status code:
1
self.get("/").assertCreated()
Copied!

assertSuccessful

Assert that the response has as status code between 200 and 300
1
self.get("/").assertSuccessful()
Copied!

assertUnauthorized

Assert that the response has as 401 status code
1
self.get("/").assertUnauthorized()
Copied!

assertForbidden

Assert that the response has as 403 status code
1
self.get("/").assertForbidden()
Copied!

assertHasHeader

Assert that the response has the given header name and value (if given).
1
self.get("/").assertHasHeader(name, value=None)
Copied!

assertHeaderMissing

Assert that the response does not have the given header.
1
self.get("/").assertHeaderMissing(name)
Copied!

assertLocation

Assert the response has the given URI value in Location header.
1
self.get("/").assertLocation(uri)
Copied!

assertRedirect

Assert that the response is a redirection to the given URI (if provided) or to the given route name with the given parameters (if provided).
1
self.get("/logout").assertRedirect(url=None, name=None, params={})
Copied!
1
self.get("/logout").assertRedirect()
2
self.get("/logout").assertRedirect("/login")
3
self.get("/login").assertRedirect(name="profile", params={"user": 1})
Copied!

assertCookie

Assert that the request contains the given cookie name and value (if provided).
1
self.get("/").assertCookie(name, value=None)
Copied!

assertPlainCookie

Assert that the request contains the given unencrypted cookie name
1
self.get("/").assertPlainCookie(name)
Copied!

assertCookieExpired

Assert that the request contains the given cookie name and is expired.
1
self.get("/").assertCookieExpired(name)
Copied!

assertCookieMissing

Assert that the request does not contain the given cookie.
1
self.get("/").assertCookieMissing(name)
Copied!

assertSessionHas

Assert that the session contains the given key and value (if provided).
1
self.get("/").assertSessionHas(name, value=None)
Copied!

assertSessionMissing

Assert that the session does not contain the given key.
1
self.get("/").assertSessionMissing(name)
Copied!

assertSessionHasErrors

Assert that the session contains an errors key or contains the given list of keys in errors key.
1
self.get("/").assertSessionHasErrors()
Copied!
1
self.get("/").assertSessionHasErrors(["email", "first_name"])
Copied!

assertSessionHasNoErrors

Assert that the session does not contain an errors key or that this key is empty.
1
self.get("/").assertSessionHasNoErrors()
Copied!

assertViewIs

Assert that the route returned the given view name.
1
self.get("/").assertViewIs("app")
Copied!

assertViewHas

Assert that view context contains a given data key and value (if provided).
1
self.get("/").assertViewHas(key, value=None)
Copied!

assertViewHasExact

Assert that view context contains exactly the given data keys. It can be a list of keys or a dictionary (here only keys will be verified).
1
self.get("/").assertViewHasExact(keys)
Copied!

assertViewMissing

Assert that given data key is not available in the view context.
1
self.get("/").assertViewMissing(key)
Copied!

assertAuthenticated

Assert that a user is authenticated after the current request.
1
self.get("/").assertAuthenticated()
Copied!

assertGuest

Assert that a user is not authenticated after the current request.
1
self.get("/").assertGuest()
Copied!

assertAuthenticatedAs

Assert that a given user is authenticated after the current request.
1
self.get("/").assertAuthenticatedAs(user)
Copied!

assertHasHttpMiddleware

Assert that the request has the given HTTP middleware. An HTTP middleware class should be provided.
1
self.get("/").assertHasHttpMiddleware(middleware_class)
Copied!
1
from app.middleware import MyAppMiddleware
2
self.get("/").assertHasHttpMiddleware(MyAppMiddleware)
Copied!

assertHasRouteMiddleware

Assert that the request has the given route middleware. The registration key of the middleware should be provided.
1
self.get("/").assertHasRouteMiddleware(middleware_name)
Copied!
1
# route_middleware = {"web": [SessionMiddleware, VerifyCsrfToken]}
2
self.get("/").assertHasRouteMiddleware("web")
Copied!

assertHasController

Assert that the route used the given controller. A class or a string can be provided. If it's a string it should be formatted as follow [email protected].
1
self.get("/").assertHasController(controller)
Copied!
1
from app.controllers import WelcomeController
2
self.get("/").assertHasController(WelcomeController)
3
self.get("/").assertHasController("[email protected]")
Copied!

assertRouteHasParameter

Assert that the route used has the given parameter name and value (if provided).
1
self.get("/").assertRouteHasParameter(key, value=None)
Copied!

assertJson

Assert that response is JSON and contains the given data dictionary (if provided). The assertion will pass even if it is not an exact match.
1
self.get("/").assertJson(data={})
Copied!
1
self.get("/").assertJson() # check that response is JSON
2
self.get("/").assertJson({"key": "value", "other": "value"})
Copied!

assertJsonPath

Assert that response is JSON and contains the given path, with eventually the given value if provided. The path can be a dotted path.
1
self.get("/").assertJsonPath(path, value=None)
Copied!
1
self.get("/").assertJsonPath("user.profile.name", "John")
Copied!

assertJsonExact

Assert that response is JSON and is strictly equal to the given dictionary.
1
self.get("/").assertJsonExact(data)
Copied!

assertJsonCount

Assert that response is JSON and has the given count of keys at root level or at the given key (if provided).
1
self.get("/").assertJsonCount(count, key=None)
Copied!

assertJsonMissing

Assert that response is JSON and does not contain given path. The path can be a dotted path.
1
self.get("/").assertJsonMissing(path)
Copied!
Last modified 2mo ago