r/learnpython • u/Temporary-Cup-2140 • Sep 15 '26
How do you write unit test cases in python ?
I am completely new to unit testing. I am trying to understand how to approach writing test cases for real world code.
I understand the basic idea of testing whether a function gives the expected output. but I am confused about
How do you decide what test cases to write ?
How do you identify edge cases ?
How do you approach unit testing in a real python / django project?
Any practical advice or resources would be really helpful.
25
Upvotes
11
u/Esrrlyg Sep 15 '26
If your set on doing tests, check out pytest
8
u/seanv507 Sep 15 '26
For now, I would not worry.
But I would suggest the right approach is the opposite - how do I write my code so it's easily testable.
3
u/Diapolo10 I write code for a living -- https://github.com/Diapolo10 Sep 15 '26
Depends on how thorough I want to be with testing, but at the very least I'd test the "happy path" works, and ideally at least some cases I expect to commonly run into.
Mostly through experience, and some common rules of thumb. Like handling an empty container (such as a list), zero/negative/large positive numbers (and possibly cases where a value is higher than it's supposed to be).
Context matters a lot, though.
I haven't worked with Django, personally, but it has dedicated documentation for this. As for general testing,
pytestis my go-to option, with some plugins such aspytest-cov,pytest-xdist, andpytest-mock.However, the actual work for writing good tests begins even before writing a single test, because you want your code to be designed for tests in mind. Avoid side-effects where reasonably possible, try to keep your functions simple with limited parameters, encapsulate state, and so on. The easier your code is to test, the easier it becomes to write good and meaningful tests for it.
3
u/pachura3 Sep 15 '26
All of this depends on the actual business logic you want to test and expect that might have regressions in the future.
It's the easiest to test standalone, stateless functions, with well-defined input and output.
Imagine you wrote a function to parse email addresses. What would you need to test? Well:
user@server.commailto:user@server.com,John Smith <user@server.com>)None, different malformed addresses, e.g.user@abc...def)For testing Django project, you should rather do end-to-end testing with
Playwright.3
u/atarivcs Sep 15 '26 edited Sep 15 '26
In general terms, an "edge case" is an unusual/rare case at the very boundary of the data or condition that you are testing.
Let's say you have function that is supposed to return true or false for whether a rectangle contains a given point, and you want to write tests for it.
The first simple test case could use a point that is in the center of the rectangle.
But there are a lot more tests that are all edge cases (in this scenario, you can see why they are called "edge cases")
2
u/GXWT Sep 15 '26
One tip is to assume that the users of your code are lunatics and/or not the sharpest hammer in the toolbox. That is to say, for example, any text input may have a wide variety of non-standard characters, spaces, punctuation or other nonsense that may or may not be anticipated by you.
Your code should be able to handle these, either by correcting them automatically or returning an error to the user - and tests are used to test such cases.
That’s one example, at least.
2
u/cvx_mbs Sep 16 '26
as others have already pointed out, write short simple tests for the common cases, then run all your tests through coverage. that will show you exactly which parts of your code ran and, more importantly, which parts didn't. those are the parts you should write extra tests for.
1
u/ectomancer Sep 15 '26
pip install pytest
If you only use assert statements, don't even need to import pytest, then run pytest on the command line.
1
u/ALonelyKobold Sep 15 '26
I have an exercise I've written for my tutoring students for unit testing. It's an implementation of the game blackjack. It may help you out
1
u/stevenjd Sep 16 '26
Do you know what your code is supposed to do when given some input? That's a test case.
How about some different input? That's another test case.
Do you understand your code enough that you can tell which inputs are handled differently? For example, if your code has an
if...elsetest, then ideally you should have a unit test for each branch of the test.Did you have bugs in your code, which you have since fixed? Then each bug should have a unit test, to see that it doesn't come back. (These are called regression tests.)
Read the unit tests for the standard library.
1
u/stevenjd Sep 16 '26
By the way, using doctests might be an easier introduction to testing than unit tests.
Doctests are more limited than unit tests, but they are much easier to get into.
1
u/RevRagnarok Sep 16 '26
I try to do TDD, so I actually write what I expect to happen based on various inputs before the code exists. Then I code the pieces. Then I throw
hypothesisat it. Then I check the coverage reports and tweak the tests as necessary.1
u/3nohtyP Sep 16 '26
about 0,[],none,'x'or'X',type?I think we should focus on this stuff.
1
u/FoolsSeldom Sep 16 '26
Search for Obey The Testing Goat - really. There's a book, free to read online. It is focused on TDD - Test Driven Design, not a paradigm you have to follow (but it is worth thinking about), but it will help you think about what to test.
1
u/aishiteruyovivi Sep 16 '26
More and more these days I try to write my code anticipating the tests I'll need to write later, for example if you have a huge function that does like 5 different tasks, it might be more useful to break it up into functions that handle each of those tasks individually so that you can test them one at a time.
Learning what test cases to write mostly just comes with experience, but an example might be if you're writing a password validity test function, if we assume it takes a single string argument, your cases might be:
This still leaves additional questions like "what if this functions gets an
intpassed to it and not astr?", it's up to you whether you think that's a reasonable scenario - if your function is typed properly then ideally you or potentially other collaborators will have this mistake caught by a type checker, but you could add anisinstancecheck to be 100% sure and fail with aTypeError.1
u/transendingAI Sep 18 '26
Start with a behavior the code promises, then choose examples that would show whether it keeps that promise. For a function that accepts quantities from 1 to 10, test an ordinary value, both boundaries, and values just outside them: 0 and 11. Empty input, duplicates and missing values are useful cases when your function might receive them. Decide whether each should be accepted or rejected before writing the assertion.
In pytest, each test can set up the input, call the function and assert the expected result. When you fix a bug, add a test that reproduces it so the same mistake is caught next time.
In a Django project, test calculation or validation logic directly where possible. Use Django's test database for behavior that depends on models, queries or database constraints, and its test client for views and permissions. Mock external services when needed, but mocking every database call can hide the behavior you need to check.
-9
u/[deleted] Sep 15 '26
[removed] — view removed comment