Getting Started
Masonite testing is very simple. You can test very complex parts of your code with ease by just extending your class with a Masonite unit test class.
Although Masonite uses pytest to run tests, Masonite's test suite is based on unittest. So you will use unittest syntax but run the tests with pytest. Because of this, all syntax will be in camelCase instead of PEP 8 lower_case_with_underscores. Just know that all TestCase assertions used during testing is in camelCase form to maintain unittest standards.

Environment

When running tests, Masonite will automatically set the environment to testing. You are free to define other testing environment configuration values as necessary.
You can create a .env.testing file. Feel free to load any testing environment variables in here. By default they will not be commited. When pytest runs it will additionally load and override any additional environment variables.

Creating Tests

You can simply create a file starting with test_ and then creating a test class inheriting from masonite TestCase class.
You can also directly use the command
1
$ python craft test SomeFeatureTest
Copied!
to create tests/unit/test_some_feature.py:
1
from masonite.tests import TestCase
2
3
4
class SomeFeatureTest(TestCase):
5
def setUp(self):
6
super().setUp()
7
8
def test_something(self):
9
self.assertTrue(True)
Copied!
That's it! You're ready to start testing. Read on to learn how to build your test cases and run them.

Running Tests

You can run tests by calling
1
$ python -m pytest
Copied!
This will automatically discover your tests following pytest automatic tests discovery. You can also run a specific test class
1
$ python -m pytest tests/unit/test_my_feature.py
Copied!
Or a specific test method
1
$ python -m pytest tests/unit/test_my_feature.py::MyFeatureTest::test_feature_is_working
Copied!
Finally you can re-run the last failed tests automatically
1
$ python -m pytest --last-failed
Copied!

Building Tests

Test Life Cycle

When you run a test class each test method of this test class will be ran following a specific life cycle.
1
class TestFeatures(TestCase):
2
3
@classmethod
4
def setUpClass(cls):
5
"""Called once before all tests of this class are executed."""
6
print("Setting up test class")
7
8
@classmethod
9
def tearDownClass(cls):
10
"""Called once after all tests of this class are executed."""
11
print("Cleaning up test class")
12
13
def setUp(self):
14
"""Called once before each test are executed."""
15
super().setUp()
16
print("Setting up individual unit test")
17
18
def tearDown(self):
19
"""Called once after each test are executed."""
20
super().tearDown()
21
print("Cleaning up individual unit test")
22
23
def test_1(self):
24
print("Running test 1")
25
26
def test_2(self):
27
print("Running test 2")
Copied!
Running the above test class will create this output:
1
Setting up test class
2
Setting up individual unit test
3
Running test 2
4
Cleaning up individual unit test
5
Setting up individual unit test
6
Running test 1
7
Cleaning up individual unit test
8
Cleaning up test class
Copied!
Note that tests methods are not always ran in the order specified in the class. Anyway you should not make the assumptions that tests will be run in a given order. You should try to make your tests idempotent.

Chaining assertions

All methods that begin with assert can be chained together to run through many assertions. All other method will return some kind of boolean or value which you can use to do your own assertions.

Asserting exceptions

Sometimes you need to assert that a given piece of code will raise a given exception. To do this you can use the standard assertRaises() context manager:
1
with self.assertRaises(ValidationError) as e:
2
# run some code here
3
raise ValidationError("An error occured !")
4
5
self.assertEqual(str(e.exception), "An error occured !")
Copied!

Capturing test output

Sometimes you need to test the output of a function that prints to the console. To do this in your tests you can use the captureOutput() context manager:
1
with self.captureOutput() as output:
2
# run some code here
3
print("Hello World !")
4
5
self.assertEqual(output.getvalue().strip(), "Hello World !")
Copied!

Helpers

Masonite comes with different helpers that can ease writing tests. Some of them have already been explained in sections above.

withExceptionsHandling

Enable exceptions handling during testing.
1
self.withExceptionsHandling()
Copied!

withoutExceptionsHandling

Disable exceptions handling during testing.
1
self.withoutExceptionsHandling()
Copied!
Note that exception handling is disabled by default during testing.

withCsrf

Enable CSRF protection during testing.
1
self.withCsrf()
Copied!

withoutCsrf

Disable CSRF protection during testing.
1
self.withoutCsrf()
Copied!
Note that CSRF protection is disabled by default during testing.

withCookies

Add cookies that will be used in the next request. This method accepts a dictionary of name / value pairs. Cookies dict is reset between each test.
1
self.withCookies(data)
Copied!

withHeaders

Add headers that will be used in the next request. This method accepts a dictionary of name / value pairs. Headers dict is reset between each test.
1
self.withHeaders(data)
Copied!

fakeTime

Set a given pendulum instance to be returned when a now (or today, tomorrow yesterday) instance is created. It's really useful during tests to check timestamps logic.
This allow to control which datetime will be returned to be able to always have an expected behaviour in the tests.
1
given_date = pendulum.datetime(2021, 2, 5)
2
self.fakeTime(given_date)
3
self.assertEqual(pendulum.now(), given_date)
Copied!
When using those helpers you should not forget to reset the default pendulum behaviour with restoreTime() helper to avoid breaking other tests. It can be done directly in the test or in a tearDown() method.

fakeTimeTomorrow

Set the mocked time as tomorrow. (It's a shortcut to avoid doing self.fakeTime(pendulum.tomorrow())).
1
tomorrow = pendulum.tomorrow()
2
self.fakeTimeTomorrow()
3
self.assertEqual(pendulum.now(), tomorrow)
Copied!

fakeTimeYesterday

Set the mocked time as yesterday.

fakeTimeInFuture

Set the mocked time as an offset of a given unit of time in the future. Unit can be specified among pendulum units: seconds, minutes, hours, days (default), weeks, months, years.
1
self.fakeTimeInFuture(offset, unit="days")
Copied!
1
real_now = pendulum.now()
2
self.fakeTimeInFuture(1, "months")
3
self.assertEqual(pendulum.now().diff(real_now).in_months(), 1)
Copied!

fakeTimeInPast

Set the mocked time as an offset of a given unit of time in the past. Unit can be specified among pendulum units: seconds, minutes, hours, days (default), weeks, months, years.
1
self.fakeTimeInPast(offset, unit="days")
Copied!

restoreTime

Restore the mocked time behaviour to default behaviour of pendulum. When using fake time helpers you should not forget to call this helper at the end.
It can be done directly in the test or in a tearDown() method.
1
def tearDown(self):
2
super().tearDown()
3
self.restoreTime()
4
5
def test_creation_date(self):
6
self.fakeTimeYesterday()
7
# from now on until the end of this unit test, time is mocked and will return yesterday time
Copied!
Last modified 2mo ago