我是新手开发者,请谅解
所以我有一个关于游戏“城镇”的代码,您在其中命名一个城镇,下一个城镇应该从上一个城镇的最后一个字符开始。
我为游戏本身编写了代码。它本身似乎可以工作,但在测试过程中出现错误。
def formatCityName( name_city):
return name_city.strip().lower().capitalize()
class Town_Game:
def startGame(self,name_city):
self.cities = set()
self.cache = set()
char = None
if not self.cities:
self.cities = {formatCityName(x) for x in open("C:/Users/bodmi/PycharmProjects/test3/cities.txt", "r", encoding="utf-8").readlines() if x.strip()}
try:
lastChar = self.isCorrectTown(name_city, char)
return str(lastChar)
except Exception as e:
return f"Error processing town: {str(e)}"
def isCorrectTown(self, name_city, char):
if (name_city in self.cities) and (name_city[0] == char or char is None) and not (name_city in self.cache):
return name_city[-1]
else:
raise ValueError(f"{name_city} is not a valid city or has already been used.")
print(Town_Game.startGame(Town_Game,"London")) #outputs "n"
特点:
Feature: I want to play a game Towns
Scenario: When i saying town name
Given Game starts
When I saying new town "London"
Then New town should be added to cache and next town should start from "n"
测试:
from behave import given, when, then
from town_game import Town_Game, formatCityName
@given('Game starts')
def step_given_calculator_running(context):
context.game = Town_Game()
@when('I saying new town {name_city}')
def step_when_enter_expression(context, name_city):
context.result = context.game.startGame(name_city)
@then('New town should be added to cache and next town should start from {expected_result}')
def step_then_verify_result(context, expected_result):
assert context.result == expected_result, \
f"Expected '{expected_result}', but got '{context.result}'"
当我运行测试时,它说:预期为“n”,但得到“处理城镇时出错:“伦敦”不是有效的城市或已被使用。”
我不知道为什么。
我是否需要将方法 formatCityName 导入到测试文件中,否则它会自行收紧?
感谢您的帮助!
这就是问题所在:
When I saying new town "London"
测试步骤定义将引号视为实际值的一部分。您的游戏代码收到
"London"
作为实际猜测,包括引号。
要么从步骤定义中去掉引号,要么调整游戏代码以去掉引号。