Quickstart: Server Testing
Check your server functions do what you expect
You can write and run tests for your server-side functions inside the Anvil Editor using pytest.
Follow this quickstart to write a function in a Server Module, write a test for it and run the test.
Create an app
Log in to Anvil and click ‘Create a new app’. Choose the Minimal Theme.
Create a new Minimal Theme app
Write a server function
In the App Browser, click ‘+ Add Server Module’ to add a new Server Module.
In ServerModule1, add a function that calculates the area of a triangle:
def calculate_triangle_area(base, height):
return (base * height) / 2Add testing to your app
Click the blue plus button
in the Sidebar Menu and choose “Testing”.
Add Testing from the Sidebar Menu
This adds a requirements.txt file with pytest already in it, and a test_examples.py file with some example tests.
Write a test
Open test_examples.py and delete its contents. We’re going to add a test for calculate_triangle_area in this file.
At the top of the file, import the function from your Server Module:
from <AppName>.ServerModule1 import calculate_triangle_areaA triangle with a base of 3 and a height of 2 has an area of 3, so we’ll add a test that checks calculate_triangle_area returns 3 for those arguments:
def test_calculate_triangle_area():
assert calculate_triangle_area(3, 2) == 3pytest only finds tests in files named test_*.py or *_test.py, and only runs functions whose names start with test_.Run your tests
In the Server Tests navigation panel, click the blue “ Run tests” button. This would run all the tests in our app if we had more.
Click the ‘Run tests’ button
to run all tests in the app.
After clicking the button, the Server Tests tab will open in the Bottom Panel. When the run finishes, you’ll see a green check mark next to test_calculate_triangle_area to show that it passed. The results pane on the right shows a summary of the run.
A passing test in the Server Tests tab
Make a test fail
Let’s see what a failing test looks like. Go back to ServerModule1, and update calculate_triangle_area so that the calculation is wrong:
def calculate_triangle_area(base, height):
return (base * height) / 3Run the test again. test_calculate_triangle_area now has a red x next to it, indicating that the test failed. Click on the test name in the list to see its output, including why it failed.
A failed test and its output in the Server Tests tab
Next up
Want more depth on this subject?
Read more about testing your server code, including running individual tests, testing emails, using App Secrets in tests and running tests from your terminal with the Anvil CLI.
Want another quickstart?
Every quickstart is on the Quickstarts page.
Do you still have questions?
Our Community Forum is full of helpful information and Anvil experts.