0% found this document useful (0 votes)
6 views2 pages

Beginners Python Cheat Sheet Pcc Testing

The document provides an overview of testing functions and classes in Python using the unittest module. It explains how to create test cases, run tests, and handle failures, emphasizing the importance of maintaining existing functionality when modifying code. Additionally, it covers the use of the setUp() method for class testing and various assert methods for validating test outcomes.

Uploaded by

vertcodefreepdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views2 pages

Beginners Python Cheat Sheet Pcc Testing

The document provides an overview of testing functions and classes in Python using the unittest module. It explains how to create test cases, run tests, and handle failures, emphasizing the importance of maintaining existing functionality when modifying code. Additionally, it covers the use of the setUp() method for class testing and various assert methods for validating test outcomes.

Uploaded by

vertcodefreepdf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Beginner's Python

Testing a function (cont.) A failing test (cont.)


Building a testcase with one unit test Running the test
To build a test case, make a class that inherits from unittest. When you change your code, it’s important to run your existing

Cheat Sheet - TestCase and write methods that begin with test_. Save this as
test_full_names.py
import unittest
tests. This will tell you whether the changes you made affected
existing behavior.
E

Testing Your Code from full_names import get_full_name

class NamesTestCase(unittest.TestCase):
================================================
ERROR: test_first_last (__main__.NamesTestCase)
Test names like Janis Joplin.
"""Tests for names.py.""" ------------------------------------------------
Why test your code? Traceback (most recent call last):
def test_first_last(self): File "test_full_names.py", line 10,
When you write a function or a class, you can also """Test names like Janis Joplin.""" in test_first_last
write tests for that code. Testing proves that your code full_name = get_full_name('janis', 'joplin')
works as it's supposed to in the situations it's designed 'joplin') TypeError: get_full_name() missing 1 required
to handle, and also when people use your programs in self.assertEqual(full_name, positional argument: 'last'
unexpected ways. Writing tests gives you confidence 'Janis Joplin')
that your code will work correctly as more people ------------------------------------------------
if __name__ == '__main__': Ran 1 test in 0.001s
begin to use your programs. You can also add new unittest.main()
features to your programs and know whether or not FAILED (errors=1)
you've broken existing behavior by running your tests. Running the test
A unit test verifies that one specific aspect of your Python reports on each unit test in the test case. The dot represents Fixing the code
a single passing test. Python informs us that it ran 1 test in less than When a test fails, the code needs to be modified until the test
code works as it's supposed to. A test case is a 0.001 seconds, and the OK lets us know that all unit tests in the test passes again. Don’t make the mistake of rewriting your tests to fit
collection of unit tests which verify that your code's case passed. your new code, otherwise your code will break for anyone who's
behavior is correct in a wide variety of situations. .
using it the same way it's being used in the failing test. Here we can
make the middle name optional.
---------------------------------------
Testing a function: a passing test Ran 1 test in 0.000s def get_full_name(first, last, middle=''):
Python's unittest module provides tools for testing your """Return a full name."""
code. To try it out, we’ll create a function that returns a full OK
name. We’ll use the function in a regular program, and then if middle:
build a test case for the function. full_name = f"{first} {middle} {last}"
Testing a function: A failing test else:
A function to test Failing tests are important; they tell you that a change in the full_name = f"{first} {last}"
Save this as full_names.py code has affected existing behavior. When a test fails, you
def get_full_name(first, last): need to modify the code so the existing behavior still works. return full_name.title()
"""Return a full name.""" Modifying the function Running the test
We’ll modify get_full_name() so it handles middle names, but Now the test should pass again, which means our original
full_name = f"{first} {last}" we’ll do it in a way that breaks existing behavior. functionality is still intact.
return full_name.title()
def get_full_name(first, middle, last): .
Using the function """Return a full name.""" ---------------------------------------
Save this as names.py full_name = f"{first} {middle} {last}" Ran 1 test in 0.000s
return full_name.title()
from full_names import get_full_name
Using the function OK
janis = get_full_name('janis', 'joplin')
print(janis) from full_names import get_full_name

bob = get_full_name('bob', 'dylan') john = get_full_name('john', 'lee', 'hooker')


print(john)
Python Crash Course
print(bob) A Hands-on, Project-Based
david = get_full_name('david', 'lee', 'roth') Introduction to Programming
print(david) nostarch.com/pythoncrashcourse2e
Adding new tests Testing a class The setUp() method
You can add as many unit tests to a test case as you need. Testing a class is similar to testing a function, since you’ll When testing a class, you usually have to make an instance
To write a new test, add a new method to your test case mostly be testing your methods. of the class. The setUp() method is run before every test.
class. Any instances you make in setUp() are available in every
A class to test
test you write.
Testing middle names Save as accountant.py
We’ve shown that get_full_name() works for first and last names.
class Accountant(): Using setUp() to support multiple tests
Let’s test that it works for middle names as well. The instance self.acc can be used in each new test.
"""Manage a bank account."""
import unittest import unittest
from full_names import get_full_name def __init__(self, balance=0): from accountant import Accountant
self.balance = balance
class NamesTestCase(unittest.TestCase): class TestAccountant(unittest.TestCase):
"""Tests for names.py.""" def deposit(self, amount): """Tests for the class Accountant."""
self.balance += amount
def test_first_last(self): def setUp(self):
"""Test names like Janis Joplin.""" def withdraw(self, amount): self.acc = Accountant()
full_name = get_full_name('janis', self.balance -= amount
'joplin') def test_initial_balance(self):
self.assertEqual(full_name, Building a testcase # Default balance should be 0.
'Janis Joplin') For the first test, we’ll make sure we can start out with different initial self.assertEqual(self.acc.balance, 0)
balances. Save this as test_accountant.py.
def test_middle(self): import unittest # Test non-default balance.
"""Test names like David Lee Roth.""" from accountant import Accountant acc = Accountant(100)
full_name = get_full_name('david', self.assertEqual(acc.balance, 100)
'roth', 'lee') class TestAccountant(unittest.TestCase):
self.assertEqual(full_name, """Tests for the class Accountant.""" def test_deposit(self):
'David Lee Roth') # Test single deposit.
def test_initial_balance(self): self.acc.deposit(100)
if __name__ == '__main__': # Default balance should be 0. self.assertEqual(self.acc.balance, 100)
unittest.main() acc = Accountant()
self.assertEqual(acc.balance, 0) # Test multiple deposits.
Running the tests self.acc.deposit(100)
The two dots represent two passing tests.
# Test non-default balance. self.acc.deposit(100)
.. acc = Accountant(100) self.assertEqual(self.acc.balance, 300)
--------------------------------------- self.assertEqual(acc.balance, 100)
Ran 2 tests in 0.000s def test_withdrawal(self):
OK if __name__ == '__main__': # Test single withdrawal.
unittest.main() self.acc.deposit(1000)
self.acc.withdraw(100)
A variety of assert methods Running the test self.assertEqual(self.acc.balance, 900)
Python provides a number of assert methods you can use to
.
test your code. --------------------------------------- if __name__ == '__main__':
Verify that a==b, or a != b Ran 1 test in 0.000s unittest.main()
OK
assertEqual(a, b) Running the tests
assertNotEqual(a, b) ...
When is it okay to modify tests?
Verify that x is True, or x is False ---------------------------------------
In general you shouldn’t modify a test once it’s written. When Ran 3 tests in 0.001s
assertTrue(x) a test fails it usually means new code you’ve written has
assertFalse(x) broken existing functionality, and you need to modify the new OK
code until all existing tests pass.
Verify an item is in a list, or not in a list If your original requirements have changed, it may be
assertIn(item, list) appropriate to modify some tests. This usually happens in
assertNotIn(item, list) the early stages of a project when desired behavior is still More cheat sheets available at
being sorted out, and no one is using your code yet. ehmatthes.github.io/pcc_2e/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy