Python 行为测试失败,但代码可以自行工作

问题描述 投票:0回答:1

我有关于游戏“城镇”的代码,您可以在其中命名一个城镇,下一个城镇应该从上一个城镇的最后一个字符开始。

它本身似乎可以工作,但在测试过程中出现错误。

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}'"

当我运行测试时,它说:

Expected '"n"', but got 'Error processing town: "London" is not a valid city or has already been used.'

为什么?

python testing bdd python-behave
1个回答
0
投票

这就是问题所在:

When I saying new town "London"

测试步骤定义将引号视为实际值的一部分,因此您的游戏代码收到

"London"
作为实际猜测,包括引号。

要么从步骤定义中删除引号,要么调整游戏代码以删除引号。

© www.soinside.com 2019 - 2024. All rights reserved.