07. Comprehensive example
We have covered quite a bit. Let’s go through an example from problem statement to implementation to test using what we’ve learned so far.
Setup
- Create a new project directory named
comp-example/
or something similar.- Mac and Ubuntu on VirtualBox users: Open that directory using PyCharm as usual.
- WSL users: Follow the setup process as the bottom of the page.
- Download each of the sample input files below and place them in the project directory:
Problem Description
We’ll start with this high-level description of the problem:
You are tasked with writing a program that can read in a text file where each line has the name of a species of bird. Your program needs to count the number of times each species appears. An example of the input is below. Ask the user to type in the name of the file they wish to be processed.
White-eared Hummingbird Townsend's Solitaire Townsend's Solitaire Yellow-fronted Canary Chestnut-fronted Macaw
Your program must handle any text file in this format.
Implementation
We’ll start by doing the simplest thing that meets the requirements of the problem description.
Writing pytest code
Finally time to test. When you write test cases and assertions, you are checking the actual computed result against the expected result for a given input.
Setup for WSL Users
You will follow this process for every project on WSL from now on.
- Open PyCharm and select the
File
menu, thenClose Project
. - Select
WSL
on the left, then the+
button to create a new project. Do this even if you already have atesting-lab/
directory. - Select the
...
button to pick the Projcet directory. - Pick your Ubuntu instance at the top, then navigate to
home/<your_id>/seng-201/
and create a new folder (icon at the top) forcomp-example/
. - Select the new directory and hit
OK
. - Click
Start IDE and Connect
on the screen. PyCharm will take a minute to finish configuring. It should open a new window with amain.py
file showing some boilerplate code. - Select the
File
menu, thenSettings
. - Select
Project: comp-example
in the left pane, then click thePython Interpreter
link. - Select the
Add Interpreter
link near the top right, thenAdd Local Interpreter
. - Leave the default options selected and hit
OK
. If you see a red error message, contact the instructor. OK
out of the settings screen.- Finally, open a new Terminal within PyCharm. Type
which pip
. You should see something like/home/<your_id>/seng-201/comp-example/.venv/bin/pip
, or;/home/<your_id>/virtualenvs/comp-example/bin/pip
- but not
/usr/bin/python
- You will run all subsequent Terminal commands from the integrated Terminal in PyCharm.
- run the following in the integrated Terminal:
pip install pytest pytest-cov
- Complete the setup instructions at the top of this lab.