You run a car dealership :material-car-side:. The inventory is tracked in two places: a database and a text file, each of which contain a set of Vehicle Identification Numbers (VINs).
They should have the same set of VINs (not necessarily in the same order).
Write a test that checks for discrepancies in the VINs. If differences exist, provide a useful message to the user for fixing them.
Directory Structure¶
vins/
vins.txt
vins.py
test_vins.py
Files¶
WP0AA2991YS620631
1G4GJ11Y9HP422546
4T1BG22K8VU176482
JH4KA3151KC019450
1FTYR14U2XPC03940
JH4DC4340RS000837
JH4DA9340MS002938
JH4DB1660LS017594
1GCDC14K2LE198114
JH4NA1260MT001906
2FMDA5146TBC22506
def fetch_vins_from_db():
"""Pretend to fetch VINs from a database.."""
vins = [
"WP0AA2991YS620631",
"JH4NA1150RT000268",
"4T1BG22K8VU176482",
"JH4KA3151KC019450",
"1FTYR14U2XPC03940",
"5GAEV23718J129013",
"JH4DA9340MS002938",
"JH4DB1660LS017594",
"1GCDC14K2LE198114",
"JH4NA1260MT001906",
"JH4DA3441JS029234",
"5TFUW5F13CX228552",
]
return vins
from vins import fetch_vins_from_db
def test_vin_discrepancies():
"""Check for discrepancies in VINs between vins.txt and the database"""
# your code here
Solution¶
from vins import fetch_vins_from_db
def test_vin_discrepancies():
"""Check for discrepancies in VINs between vins.txt and the database"""
# load VINs from database
vins_db = fetch_vins_from_db()
# Load VINs from text file
vins_file = open('vins.txt', 'r')
vins_txt = vins_file.read().splitlines()
# Convert to sets for easy comparison
vins_db = set(vins_db)
vins_txt = set(vins_txt)
# Check for VINs in db not in txt and vice versa
vins_db_not_tx = vins_db - vins_txt
vins_txt_not_db = vins_txt - vins_db
assert len(vins_db_not_tx) == 0 and len(vins_txt_not_db) == 0, \
f"VIN discrepancies found!\n" \
f"VINs in database not in vins.txt: {vins_db_not_tx}\n" \
f"VINs in vins.txt not in database: {vins_txt_not_db}"
Explanation¶
The strategy here is to represent each collection of VINs as a set. Then we can use set differences to get the values in one set not in the other.
In order to report a useful error message, we place an f-string alongside the assertion as described here.