这涉及从数据库访问数据,并在 python 中处理数据。数据库名称为inb104,包含两个表car_details和cars_for_sale
到目前为止,这是我的代码
def top_N_models(carbrand, num_of_highest):
connection = MySQLdb.connect(host='localhost', user='root', \
passwd='root', db='inb104')
cursor = connection.cursor()
sql = str("SELECT model, COUNT(model) AS Count FROM \
cars_for_sale WHERE make='"+carbrand+"' GROUP BY \
model ORDER BY count DESC, model LIMIT "+str(num_of_highest))
cursor.execute(sql)
rows = cursor.fetchall()
try:
test = rows[0][0]
except:
print "No such make of car!"
for row in rows:
print str(row[0]), str(row[1])
cursor.close()
connection.close()
现在,当这段代码通过一系列测试用例运行时,结果如下。在失败的测试用例中,它期望什么都不返回,而不是“没有这样的汽车!”
Trying:
top_N_models('BMW', 6)
Expecting:
3 152
X5 72
5 39
1 19
7 9
M3 9
ok
Trying:
top_N_models('TOYOTA', 10)
Expecting:
COROLLA 275
LANDCRUISER 193
RAV4 189
HILUX 179
CAMRY 137
ECHO 69
KLUGER 61
YARIS 56
AURION 22
TARAGO 22
ok
Trying:
top_N_models('HOLDEN', 1)
Expecting:
COMMODORE 426
ok
Trying:
top_N_models('EDSEL', 10)
Expecting:
No such make of car!
ok
Trying:
top_N_models('TOYOTA', 0)
Expecting nothing
**********************************************************************
File "__main__", line 34, in __main__
Failed example:
top_N_models('TOYOTA', 0)
Expected nothing
Got:
No such make of car!
Trying:
top_N_models('MINI', 1)
Expecting:
COOPER 34
ok
Trying:
top_N_models('HSV', 10)
Expecting:
CLUBSPORT 21
COUPE 5
MALOO 5
AVALANCHE 2
GTS 2
GRANGE 1
ok
1 items had no tests:
__main__.top_N_models
**********************************************************************
1 items had failures:
1 of 7 in __main__
7 tests in 2 items.
6 passed and 1 failed.
***Test Failed*** 1 failures.