Tests impress in a backend internship when they are small, readable, and aimed at behaviour that could actually break: input validation, status codes, boundaries and error paths. A reviewer trusts a 12-test suite that names its scenarios clearly more than a 90% coverage badge built from tests that assert nothing. This guide gives you a complete pytest starter template, a coverage-versus-value checklist and a 14-day plan you can follow.
What a Reviewer Looks For in an Intern’s Test Suite
Mentors reviewing intern work rarely run a coverage tool first. They open the tests folder and read test names. Within a minute they can tell whether you understood the feature or just ran code to turn lines green. Five signals separate strong suites from weak ones:
- Names that describe behaviour.
test_create_task_rejects_blank_titlebeatstest_create_1. - One reason to fail. Each test checks one rule, so a red test points to one problem.
- Edge cases chosen on purpose. Empty strings, maximum lengths, missing fields, duplicate requests and unknown IDs.
- Independence. Tests pass in any order and leave no shared state behind.
- Fast runs. The whole suite finishes in seconds, so people actually run it.
Project Layout for a Small Pytest Backend Project
The template below uses a tiny task-manager API built with FastAPI. The same structure works for Flask or Django with small changes to the client fixture. Everything here is illustrative: adapt names to your own project, and run the code yourself before relying on it.
task_api/
app/
__init__.py
service.py # pure functions: validation, formatting
main.py # FastAPI routes, in-memory store
tests/
conftest.py # shared fixtures
test_service.py # unit tests
test_api.py # API tests
test_edges.py # edge cases and error paths
pytest.ini
requirements-dev.txt
Keeping business rules in service.py as plain functions is the single best design choice for testability. Pure functions need no server, no database and no mocking.
Configuration files
# pytest.ini
[pytest]
testpaths = tests
addopts = -ra -q
markers =
edge: boundary and error-path tests
# requirements-dev.txt
pytest
pytest-cov
httpx
fastapi
The code under test (illustrative)
# app/service.py
MAX_TITLE = 100
def normalise_title(title: str) -> str:
cleaned = " ".join(title.split())
if not cleaned:
raise ValueError("title must not be blank")
if len(cleaned) > MAX_TITLE:
raise ValueError("title too long")
return cleaned
# app/main.py
from itertools import count
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from app.service import normalise_title
app = FastAPI()
TASKS = {}
_ids = count(1)
class TaskIn(BaseModel):
title: str
def reset_store():
global _ids
TASKS.clear()
_ids = count(1)
@app.post("/tasks", status_code=201)
def create_task(body: TaskIn):
try:
title = normalise_title(body.title)
except ValueError as exc:
raise HTTPException(status_code=422, detail=str(exc))
task_id = next(_ids)
TASKS[task_id] = {"id": task_id, "title": title, "done": False}
return TASKS[task_id]
@app.get("/tasks/{task_id}")
def get_task(task_id: int):
if task_id not in TASKS:
raise HTTPException(status_code=404, detail="task not found")
return TASKS[task_id]
Free 2-Week CareerSwami Internship
Online, 14 days, with a free offer letter and a free completion certificate once you finish the work. Check with your college that it fits your requirement before you enrol.
Shared Fixtures in conftest.py
Fixtures give every test a clean starting point. The autouse reset below is what keeps tests independent of each other.
# tests/conftest.py
import pytest
from fastapi.testclient import TestClient
from app.main import app, reset_store
@pytest.fixture(autouse=True)
def clean_store():
reset_store()
yield
reset_store()
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def created_task(client):
response = client.post("/tasks", json={"title": "Write tests"})
return response.json()
Unit Tests for Pure Business Logic
Start here because these tests are fast and teach you the habit of testing behaviour rather than implementation.
# tests/test_service.py
import pytest
from app.service import normalise_title, MAX_TITLE
def test_normalise_title_trims_outer_spaces():
assert normalise_title(" buy milk ") == "buy milk"
def test_normalise_title_collapses_inner_whitespace():
assert normalise_title("buy fresh milk") == "buy fresh milk"
@pytest.mark.parametrize("bad", ["", " ", "\t\n"])
def test_normalise_title_rejects_blank_values(bad):
with pytest.raises(ValueError, match="blank"):
normalise_title(bad)
def test_normalise_title_accepts_exact_maximum_length():
assert len(normalise_title("a" * MAX_TITLE)) == MAX_TITLE
def test_normalise_title_rejects_one_over_maximum():
with pytest.raises(ValueError, match="too long"):
normalise_title("a" * (MAX_TITLE + 1))
Note the boundary pair: exactly 100 characters passes and 101 fails. Boundary pairs catch off-by-one bugs that ordinary examples miss.
API Tests That Check the Contract
An API test checks what a client would see: status code, response body shape and side effects. Avoid reaching into internal variables when the API itself can confirm the result.
# tests/test_api.py
def test_create_task_returns_201_and_body(client):
response = client.post("/tasks", json={"title": " Learn pytest "})
assert response.status_code == 201
body = response.json()
assert body["title"] == "Learn pytest"
assert body["done"] is False
assert body["id"] == 1
def test_created_task_can_be_fetched(client, created_task):
response = client.get(f"/tasks/{created_task['id']}")
assert response.status_code == 200
assert response.json() == created_task
def test_ids_increase_for_each_new_task(client):
first = client.post("/tasks", json={"title": "one"}).json()
second = client.post("/tasks", json={"title": "two"}).json()
assert second["id"] == first["id"] + 1
Edge-Case and Error-Path Tests
This file is where interns stand out. Anyone tests the happy path; fewer people test what happens with bad input.
# tests/test_edges.py
import pytest
pytestmark = pytest.mark.edge
def test_unknown_task_returns_404(client):
response = client.get("/tasks/999")
assert response.status_code == 404
assert response.json()["detail"] == "task not found"
def test_blank_title_returns_422(client):
response = client.post("/tasks", json={"title": " "})
assert response.status_code == 422
def test_missing_title_field_returns_422(client):
response = client.post("/tasks", json={})
assert response.status_code == 422
def test_wrong_type_for_title_is_rejected(client):
response = client.post("/tasks", json={"title": ["not", "a", "string"]})
assert response.status_code == 422
def test_non_numeric_id_is_rejected(client):
response = client.get("/tasks/abc")
assert response.status_code == 422
def test_rejected_request_does_not_consume_an_id(client):
client.post("/tasks", json={"title": ""})
good = client.post("/tasks", json={"title": "valid"}).json()
assert good["id"] == 1
The last test checks a side effect of a failure, which is an easy thing to miss. Run only these with pytest -m edge.
Coverage-Versus-Value Checklist for Backend Interns
Run pytest --cov=app --cov-report=term-missing to see which lines were never executed. Treat the number as a question, not a goal. Use the table to decide where a new test earns its place.
| Code area | Test value | What to test | What to skip |
|---|---|---|---|
| Validation rules | High | Blank, boundary, wrong-type and missing input | Re-testing the framework’s own type checks beyond one example |
| Business calculations | High | Normal, zero, negative and maximum values | Trivial getters |
| Status codes and error bodies | High | 201, 404, 422 and any custom errors | Exact wording of every message unless clients rely on it |
| Authentication and permissions | High | No token, wrong user, expired token | Library internals |
| Database queries | Medium | Filters, ordering, empty results | Simple pass-through reads |
| Config and startup code | Low | One smoke test that the app starts | Line-by-line coverage |
Logging and __repr__ |
Low | Only if behaviour depends on it | Most of it |
Ten questions to ask before adding a test
- If this behaviour broke, would a user or another service notice?
- Does the test fail for the right reason when I temporarily break the code?
- Does it assert a result, not just call the function?
- Is the name readable as a sentence about behaviour?
- Does it depend on test order, the clock, the network or a random value?
- Is a boundary covered on both sides?
- Is one failure path tested for every success path?
- Would a parametrized test replace three near-identical ones?
- Am I mocking something I own? If so, a real in-memory version may be simpler.
- Can a teammate understand this test without opening the source?
Reading a Coverage Report: An Illustrative Worked Example
Suppose a coverage run on the task API (illustrative numbers, not a real run) shows this:
| File | Coverage | Missing lines | Verdict |
|---|---|---|---|
| app/service.py | 100% | none | Fine, and boundaries are covered |
| app/main.py | 86% | the 404 branch in get_task |
Add a test: this is a user-facing error path |
| app/config.py | 40% | environment loading | Add one smoke test; do not chase the rest |
The overall figure might read 82%. The tempting move is to write quick tests for config.py to reach 90%. The better move is to add the 404 test first, because that missing line is a real client-facing behaviour. After that, a mentor reading your pull request sees a short note such as “Raised coverage on error handling; left config loading to a single smoke test because it is thin” and understands your judgment. A number reached by judgment reads very differently from a number reached by padding.
ICFAI Himachal Pradesh Students: Fitting Backend Tests Into Your Internship Context
ICFAI University, Himachal Pradesh is described on its about page as established under the ICFAI University (Establishment and Regulation) Act 2011 and sponsored by The ICFAI Society. Its homepage lists programmes across Engineering, Management, Pharmacy, Law, Science and Arts, so students arriving at a Python backend internship come from very different backgrounds. A clean test suite is a useful equaliser: it shows ability regardless of branch.
The university’s Summer Internship page describes a faculty-supervised programme built on time-bound company projects that apply classroom concepts. That framing suits a test-focused deliverable, since a short, well-tested project gives your faculty supervisor something concrete to evaluate. The page does not state a duration, credits, evaluation scheme or whether online internships are accepted, so do not assume a free online internship will be counted for university requirements.
MBA students should note that the MBA programme page says a Summer Internship Program follows Semester II and lists a Summer Internship Project in Semester III. It also lists Business Analytics and Computer Applications as Semester I options, which makes Python data and backend skills relevant for analytics-leaning MBA students. The page labels its structure tentative, so read the current version.
For support, the Placements page mentions a training and placement officer for placements and internship opportunities, and says placement is a joint effort in which students are responsible for their own effort. Practically, that means you should build a portfolio the officer can point to: a repository with tests and a short README.
Verification steps before you start:
- Email your faculty coordinator and ask whether an online, self-arranged internship can be reported for your programme, and in what format.
- Ask for the current internship or project-work regulation document for your batch, and check the required duration and evaluation method.
- Ask in writing which documents the university needs: offer letter, completion certificate, supervisor report or a faculty-signed form.
- Check whether your faculty supervisor must approve the project topic before you begin.
- Contact the training and placement officer and ask whether they review student portfolios or GitHub links.
- Save every reply as an email so you have a record to attach to your report.
A 14-Day Plan for Building the Test Suite
If you join the free two-week online internship at CareerSwami, which includes a free offer letter and a free completion certificate after successful completion, you can use this plan inside the 14 days. It works with any of the 26 tracks that involve writing Python code.
| Days | Focus | Deliverable |
|---|---|---|
| 1-2 | Set up virtual environment, install pytest, create the layout above | One passing smoke test |
| 3-4 | Move business rules into pure functions | Unit tests with parametrize |
| 5-6 | Build two or three endpoints | API tests for success paths |
| 7-8 | Add fixtures and reset logic | Tests that pass in random order |
| 9-10 | Edge cases and error paths | Boundary pairs, 404 and 422 tests |
| 11 | Run coverage and apply the checklist | Two or three high-value tests added |
| 12 | Break the code on purpose | Confirm tests fail when they should |
| 13 | Write the README | How to run tests, what is covered and why |
| 14 | Final cleanup and submission | Clean repository link ready to share |
Habits That Make Test Suites Look Amateur
- Assertions that cannot fail.
assert responsepasses for almost any response object. Assert a status code and a field. - Tests that share state. If test B needs test A to run first, the suite will fail unpredictably.
- Copy-pasted tests. Three tests that differ only in input belong in one parametrized test.
- Heavy mocking of your own code. If everything is mocked, the test checks the mocks.
- Chasing 100%. Coverage of trivial lines costs time and adds little. Explain any deliberate gap in the README.
- No failing-first check. A new test should be seen failing at least once, by breaking the code briefly, before you trust it.
Presenting Your Tests in a Pull Request or Report
Your tests are only as impressive as your explanation of them. In the README or report, include:
- The command to run the suite and the command for coverage.
- A short list of behaviours covered: validation, status codes, boundaries.
- One paragraph on what you intentionally did not test and why.
- The coverage figure with a sentence of context, not as a headline.
Do not paste coverage numbers you have not generated yourself from your own repository.
Frequently Asked Questions
Do I need a database to write meaningful backend tests?
No. Start with pure functions and an in-memory store, as in the template. Add database tests later using a temporary SQLite file or a test database, but only after the core rules are covered.
Should I use pytest or unittest in my internship?
Pytest is the more common choice in current Python teams because of plain assert statements, fixtures and parametrization. If your mentor’s project already uses unittest, follow the project convention; pytest can also run unittest-style tests.
What coverage percentage should I aim for as a ICFAI University student?
There is no universal target. Cover validation, business rules and error paths thoroughly, then read the missing-lines report. A project with 75% coverage that tests every user-facing failure is stronger than 95% built from empty assertions.
How many tests are enough for a 14-day internship project?
For a small API with three or four endpoints, roughly 20 to 35 well-named tests is a realistic range. Quality of scenarios matters more than the count, so use the checklist above to choose.
Can I test an API without running a server?
Yes. FastAPI’s TestClient and Flask’s test client call the application directly in-process, so there is no port to open and tests run in milliseconds. This is what the template uses.
Will my university accept an online internship that includes this project?
That depends on your programme’s rules and your faculty supervisor. The university’s public internship page does not spell out acceptance of online internships, so ask your coordinator in writing and keep the reply with your documents.
How do I show that my tests actually catch bugs?
Temporarily break the code, for example change the length limit from 100 to 101, and run the suite. A boundary test should fail. Mention this check in your README as a short note on how you validated the suite.
Should I test the framework’s built-in validation?
Test it once per rule you rely on, such as a missing field returning 422, so you document the contract. Do not write dozens of tests proving the framework works.
Related Python & Backend Engineering guides
- Palamuru University Students: Applying for Python Backend Internships With No Referrals
- Fakir Mohan University Students: Learning SQL Through a Backend Internship Library Project
- Avantika University Students: Shipping a Small Backend Feature in Two Weeks
- All Python & Backend Engineering internship guides
Ready to put this into practice?
Join the free two-week CareerSwami online internship in Python & Backend Engineering. The internship, the offer letter and the completion certificate are free.














